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

84 lines
1.9 KiB
Go
Raw Normal View History

2016-12-05 07:20:27 +02:00
package jsoniter
import (
"reflect"
"strconv"
2016-12-05 07:20:27 +02:00
"testing"
"time"
"unsafe"
2017-05-05 02:22:19 +02:00
"github.com/json-iterator/go/require"
2016-12-05 07:20:27 +02:00
)
func Test_customize_type_decoder(t *testing.T) {
RegisterTypeDecoder("time.Time", func(ptr unsafe.Pointer, iter *Iterator) {
t, err := time.ParseInLocation("2006-01-02 15:04:05", iter.ReadString(), time.UTC)
if err != nil {
iter.Error = err
return
}
*((*time.Time)(ptr)) = t
})
defer CleanDecoders()
2016-12-05 07:20:27 +02:00
val := time.Time{}
err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
if err != nil {
t.Fatal(err)
}
year, month, day := val.Date()
if year != 2016 || month != 12 || day != 5 {
t.Fatal(val)
}
}
2017-05-05 02:22:19 +02:00
func Test_customize_type_encoder(t *testing.T) {
should := require.New(t)
RegisterTypeEncoder("time.Time", func(ptr unsafe.Pointer, stream *Stream) {
t := *((*time.Time)(ptr))
stream.WriteString(t.UTC().Format("2006-01-02 15:04:05"))
})
defer CleanEncoders()
val := time.Unix(0, 0)
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`"1970-01-01 00:00:00"`, str)
}
2016-12-05 07:20:27 +02:00
type Tom struct {
field1 string
}
func Test_customize_field_decoder(t *testing.T) {
RegisterFieldDecoder("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
})
defer CleanDecoders()
2016-12-05 07:20:27 +02:00
tom := Tom{}
err := Unmarshal([]byte(`{"field1": 100}`), &tom)
if err != nil {
t.Fatal(err)
}
2016-12-12 13:06:33 +02:00
}
type TestObject1 struct {
2016-12-17 11:38:13 +02:00
field1 string
}
func Test_customize_field_by_extension(t *testing.T) {
2016-12-17 11:38:13 +02:00
RegisterExtension(func(type_ reflect.Type, field *reflect.StructField) ([]string, DecoderFunc) {
if type_.String() == "jsoniter.TestObject1" && field.Name == "field1" {
return []string{"field-1"}, func(ptr unsafe.Pointer, iter *Iterator) {
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
2016-12-17 11:38:13 +02:00
}
}
return nil, nil
})
obj := TestObject1{}
err := Unmarshal([]byte(`{"field-1": 100}`), &obj)
2016-12-17 11:38:13 +02:00
if err != nil {
t.Fatal(err)
}
if obj.field1 != "100" {
t.Fatal(obj.field1)
2016-12-17 11:38:13 +02:00
}
}