废话不多说,直接上代码
package main
import (
"fmt"
"encoding/json"
)
type Test struct {
A string
B int
C string
}
func (t *Test) UnmarshalJSON(data []byte) error {
type testAlias Test
test := &testAlias{
A: "default A",
B: -2,
}
_ = json.Unmarshal(data, test)
*t = Test(*test)
return nil
}
var example []byte = []byte(`[{"A": "1", "C": "3"}, {"A": "4", "B": 2}, {"C": "5"}]`)
func main() {
out := &[]Test{}
_ = json.Unmarshal(example, &out)
fmt.Print(out)
}
结果
&[{1 -2 3} {4 2 } {default A -2 5}]
可以看到 在key没有的情况下可以指定对应的值,这样就可以了。