jsoniter_optional_test.go 997 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package jsoniter
  2. import (
  3. "github.com/json-iterator/go/require"
  4. "testing"
  5. )
  6. func Test_encode_optional_int_pointer(t *testing.T) {
  7. should := require.New(t)
  8. var ptr *int
  9. str, err := MarshalToString(ptr)
  10. should.Nil(err)
  11. should.Equal("null", str)
  12. val := 100
  13. ptr = &val
  14. str, err = MarshalToString(ptr)
  15. should.Nil(err)
  16. should.Equal("100", str)
  17. }
  18. func Test_decode_struct_with_optional_field(t *testing.T) {
  19. should := require.New(t)
  20. type TestObject struct {
  21. field1 *string
  22. field2 *string
  23. }
  24. obj := TestObject{}
  25. UnmarshalFromString(`{"field1": null, "field2": "world"}`, &obj)
  26. should.Nil(obj.field1)
  27. should.Equal("world", *obj.field2)
  28. }
  29. func Test_encode_struct_with_optional_field(t *testing.T) {
  30. should := require.New(t)
  31. type TestObject struct {
  32. field1 *string
  33. field2 *string
  34. }
  35. obj := TestObject{}
  36. world := "world"
  37. obj.field2 = &world
  38. str, err := MarshalToString(obj)
  39. should.Nil(err)
  40. should.Contains(str, `"field1":null`)
  41. should.Contains(str, `"field2":"world"`)
  42. }