1
0
mirror of https://github.com/json-iterator/go.git synced 2024-11-24 08:22:14 +02:00
json-iterator/jsoniter_interface_test.go

94 lines
2.2 KiB
Go
Raw Normal View History

2017-01-09 15:00:01 +02:00
package jsoniter
import (
"testing"
"github.com/json-iterator/go/require"
2017-01-25 17:25:25 +02:00
"unsafe"
2017-01-09 15:00:01 +02:00
)
func Test_write_array_of_interface(t *testing.T) {
should := require.New(t)
array := []interface{}{"hello"}
str, err := MarshalToString(array)
should.Nil(err)
should.Equal(`["hello"]`, str)
2017-01-25 16:43:57 +02:00
}
func Test_write_map_of_interface(t *testing.T) {
should := require.New(t)
val := map[string]interface{}{"hello":"world"}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"hello":"world"}`, str)
}
2017-02-03 12:44:54 +02:00
func Test_write_map_of_interface_in_struct(t *testing.T) {
type TestObject struct {
Field map[string]interface{}
}
should := require.New(t)
val := TestObject{map[string]interface{}{"hello":"world"}}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"Field":{"hello":"world"}}`, str)
}
func Test_write_map_of_interface_in_struct_with_two_fields(t *testing.T) {
type TestObject struct {
Field map[string]interface{}
Field2 string
}
should := require.New(t)
val := TestObject{map[string]interface{}{"hello":"world"}, ""}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"Field":{"hello":"world"},"Field2":""}`, str)
}
2017-01-25 16:43:57 +02:00
type MyInterface interface {
2017-01-25 17:25:25 +02:00
Hello() string
}
type MyString string
func (ms MyString) Hello() string {
return string(ms)
2017-01-25 16:43:57 +02:00
}
func Test_write_map_of_custom_interface(t *testing.T) {
should := require.New(t)
2017-01-25 17:25:25 +02:00
myStr := MyString("world")
should.Equal("world", myStr.Hello())
val := map[string]MyInterface{"hello":myStr}
2017-01-25 16:43:57 +02:00
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"hello":"world"}`, str)
}
func Test_write_interface(t *testing.T) {
should := require.New(t)
var val interface{}
val = "hello"
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`"hello"`, str)
2017-01-25 17:25:25 +02:00
}
func Test_read_interface(t *testing.T) {
should := require.New(t)
var val interface{}
err := UnmarshalFromString(`"hello"`, &val)
should.Nil(err)
should.Equal("hello", val)
}
func Test_read_custom_interface(t *testing.T) {
should := require.New(t)
var val MyInterface
RegisterTypeDecoder("jsoniter.MyInterface", func(ptr unsafe.Pointer, iter *Iterator) {
*((*MyInterface)(ptr)) = MyString(iter.ReadString())
})
err := UnmarshalFromString(`"hello"`, &val)
should.Nil(err)
should.Equal("hello", val.Hello())
2017-01-09 15:00:01 +02:00
}