You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The callback will be called for the registered type. The first argument is a pointer to the instance, the second argument is the iterator pointint to the next value to read.
40
+
41
+
# Customize field decoding
42
+
43
+
We can also control how the deconding is done at the field level. For example if the input is int, and we want to bind it to a string typed field.
44
+
45
+
```go
46
+
typeTomstruct {
47
+
field1 string
48
+
}
49
+
```
50
+
51
+
and the input `{"field1": 100}`. We need to register a field decoder:
52
+
53
+
```go
54
+
RegisterFieldDecoder("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
55
+
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
56
+
})
57
+
deferClearDecoders()
58
+
tom:=Tom{}
59
+
err:=Unmarshal([]byte(`{"field1": 100}`), &tom)
60
+
if err != nil {
61
+
t.Fatal(err)
62
+
}
63
+
```
64
+
65
+
It is nearly the same as type decoder, just add a argument to specify the field name.
66
+
67
+
# Customize field mapping
68
+
69
+
When the field name does not match the json input, we can customize it by callback. The callback will be provided with `reflect.StructField`, which has tags for the field.
70
+
71
+
```go
72
+
RegisterExtension(func(type_reflect.Type, field *reflect.StructField) ([]string, DecoderFunc) {
73
+
if (type_.String() == "jsoniter.Tom" && field.Name == "field1") {
0 commit comments