可以说我有这种类型:
type Foo struct{
Bar string `json:"bar"`
}
Run Code Online (Sandbox Code Playgroud)
我想将这个 json 解组到其中:
in := []byte(`{"bar":"aaa", "baz":123}`)
foo := &Foo{}
json.Unmarshal(in,foo)
Run Code Online (Sandbox Code Playgroud)
会成功就好。我想至少知道处理中跳过了某些字段。有什么好的方法可以获取这些信息吗?
您可能知道,您可以将任何有效的 json 解组到map[string]interface{}
. 解组到实例后,Foo
已经没有可用的元数据,您可以在其中检查被排除的字段或类似的内容。但是,您可以将两种类型解组,然后检查映射中是否有与 上的字段不对应的键Foo
。
in := []byte(`{"bar":"aaa", "baz":123}`)
foo := &Foo{}
json.Unmarshal(in,foo)
allFields := &map[string]interface{}
json.Unmarshal(in, allFields)
for k, _ := range allFields {
fmt.Println(k)
// could also use reflect to get field names as string from Foo
// the get the symmetric difference by nesting another loop here
// and appending any key that is in allFields but not on Foo to a slice
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2290 次 |
最近记录: |