1
0
mirror of https://github.com/json-iterator/go.git synced 2025-03-23 21:09:11 +02:00

support Any as field type

This commit is contained in:
Tao Wen 2017-04-28 09:09:24 +08:00
parent e5476f70e7
commit 8711c74c85
3 changed files with 30 additions and 1 deletions

View File

@ -361,6 +361,9 @@ func (p prefix) addToEncoder(encoder Encoder, err error) (Encoder, error) {
}
func decoderOfType(typ reflect.Type) (Decoder, error) {
if typ.ConvertibleTo(anyType) {
return &anyCodec{}, nil
}
typeName := typ.String()
typeDecoder := typeDecoders[typeName]
if typeDecoder != nil {

View File

@ -36,4 +36,17 @@ func Test_iterator_and_bind_api(t *testing.T) {
iter.ReadVal(&user)
iter.ReadArray() // array end
fmt.Println(user)
}
}
type TaskBidLog struct {
age int
}
func Test2(t *testing.T) {
rawString :=`
{"id":0,"bidId":"bid01492692440885","impId":"imp0","taskId":"1024","bidPrice":80,"winPrice":0,"isWon":0,"createTime":1492692440885,"updateTime":null,"device":"","age":30,"gender":"","location":"[中国, 山西, , ]","conType":"0","os":"iOS","osv":"","brand":"","geo":"","ip":"1.68.4.193","idfa":"","waxUserid":""}`
var log TaskBidLog
err := UnmarshalFromString(rawString, &log)
fmt.Println(err)
fmt.Println(log.age)
}

View File

@ -171,4 +171,17 @@ func Test_omit_empty(t *testing.T) {
str, err := MarshalToString(&obj)
should.Nil(err)
should.Equal(`{"field-2":"hello"}`, str)
}
func Test_any_within_struct(t *testing.T) {
should := require.New(t)
type TestObject struct {
Field1 Any
Field2 Any
}
obj := TestObject{}
err := UnmarshalFromString(`{"Field1": "hello", "Field2": [1,2,3]}`, &obj)
should.Nil(err)
should.Equal("hello", obj.Field1.ToString())
should.Equal("[1,2,3]", obj.Field2.ToString())
}