c := jsoniter.Config{DisallowUnknownFields:true}.Froze()
// json串中包含未知字段"Weight"
if err := c.UnmarshalFromString(`{"Name":"Allen","Age":18,"Height":180.43,"Weight":60.56}`, &std); err == nil{
fmt.Println(std)
}else{
fmt.Println(err)
// Output
// main.Student.ReadObject: found unknown field: Weight, error found in #10 byte of ...|3,"Weight":60.56}|..., bigger context ...|{"Name":"Allen","Age":18,"Height":180.43,"Weight":60.56}|...
}
复制代码
TagKey
指定tag字符串,默认情况为"json",我们可以指定成另一个字符串
type Student struct{
Name string `jsoniter:"name"`
Age int
Height float32 `jsoniter:"-"`
}
// 将tag指定为"jsoniter"
c := jsoniter.Config{TagKey:"jsoniter"}.Froze()
if s, err := c.MarshalToString(Student{"Allen", 18, 180.43}); err == nil{
fmt.Println(s)
// Output:
// {"name":"Allen","Age":18}
}
复制代码
OnlyTaggedField
当开启该选项时,只有带上tag的结构体字段才会被序列化输出
type Student struct{
Name string `json:"name"`
Age int
Height float32 `json:",omitempty"`
}
c := jsoniter.Config{OnlyTaggedField:true}.Froze()
if s, err := c.MarshalToString(Student{"Allen", 18, 180.43}); err == nil{
"excerpt": "Welcome to Metabase\u0026#39;s discussion forum. This is a place to get help on installation, setting up as well as sharing tips and tricks.",
"category_id": 1,
"unseen": false,
"slug": "welcome-to-metabases-discussion-forum",
"fancy_title": "Welcome to Metabase\u0026rsquo;s Discussion Forum",
"excerpt": "Welcome to Metabase\u0026#39;s discussion forum. This is a place to get help on installation, setting up as well as sharing tips and tricks.",
"category_id": 1,
"unseen": false,
"slug": "welcome-to-metabases-discussion-forum",
"fancy_title": "Welcome to Metabase\u0026rsquo;s Discussion Forum",
iter := jsoniter.ParseString(jsoniter.ConfigDefault, jsonStr)
iter.ReadObjectCB(func(iter *jsoniter.Iterator, field string) bool{
fieldList = append(fieldList, field)
iter.Skip()
return true
})
fmt.Println(fieldList)
// 输出:[_id about address age balance company email eyeColor favoriteFruit gender greeting guid index isActive latitude longitude name phone picture registered tags]