1
0
mirror of https://github.com/json-iterator/go.git synced 2025-01-23 18:54:21 +02:00
json-iterator/jsoniter_optional_test.go

47 lines
997 B
Go
Raw Normal View History

2017-01-09 20:51:09 +08:00
package jsoniter
import (
"github.com/stretchr/testify/require"
2017-06-06 23:27:00 +08:00
"testing"
2017-01-09 20:51:09 +08:00
)
func Test_encode_optional_int_pointer(t *testing.T) {
should := require.New(t)
var ptr *int
str, err := MarshalToString(ptr)
should.Nil(err)
should.Equal("null", str)
val := 100
ptr = &val
str, err = MarshalToString(ptr)
should.Nil(err)
should.Equal("100", str)
}
func Test_decode_struct_with_optional_field(t *testing.T) {
should := require.New(t)
type TestObject struct {
2017-06-13 17:47:40 +08:00
Field1 *string
Field2 *string
2017-01-09 20:51:09 +08:00
}
obj := TestObject{}
UnmarshalFromString(`{"field1": null, "field2": "world"}`, &obj)
2017-06-13 17:47:40 +08:00
should.Nil(obj.Field1)
should.Equal("world", *obj.Field2)
2017-01-09 20:51:09 +08:00
}
func Test_encode_struct_with_optional_field(t *testing.T) {
should := require.New(t)
type TestObject struct {
2017-06-13 17:47:40 +08:00
Field1 *string
Field2 *string
2017-01-09 20:51:09 +08:00
}
obj := TestObject{}
world := "world"
2017-06-13 17:47:40 +08:00
obj.Field2 = &world
2017-01-09 20:51:09 +08:00
str, err := MarshalToString(obj)
should.Nil(err)
2017-06-13 17:47:40 +08:00
should.Contains(str, `"Field1":null`)
should.Contains(str, `"Field2":"world"`)
2017-06-06 23:27:00 +08:00
}