解组未知字段的JSON [英] Unmarshal JSON with unknown fields
本文介绍了解组未知字段的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON
{a:1,b:2,?:1 ,??:1}
我知道它有a和b字段,但我不知道其他字段的名称。所以我想用以下类型解组它:
type Foo struct {
//已知字段
一个int`json:a`
B int`json:b`
//未知字段
X map [string] interface {}`json:`` //其余的领域应该去这里。
}
我该怎么做?
Unmarshaler 来实现:
type _Foo Foo
func(f * Foo)UnmarshalJSON(bs [] byte)(err error){
foo: = _Foo {}
if err = json.Unmarshal(bs,& foo); err == nil {
* f = Foo(foo)
}
$ bm:= make(map [string] interface {})
if err = json.Unmarshal(bs,& m); err == nil {
delete(m,a)
delete(m,b)
fX = m
}
return err
类型 _Foo
是解码时避免递归所必需的。
I have the following JSON
{"a":1, "b":2, "?":1, "??":1}
I know that it has the "a" and "b" fields, but I don't know the names of other fields. So I want to unmarshal it in the following type:
type Foo struct {
// Known fields
A int `json:"a"`
B int `json:"b"`
// Unknown fields
X map[string]interface{} `json:???` // Rest of the fields should go here.
}
How do I do that?
解决方案
It's not nice, but you could to it by implementing Unmarshaler
:
type _Foo Foo
func (f *Foo) UnmarshalJSON(bs []byte) (err error) {
foo := _Foo{}
if err = json.Unmarshal(bs, &foo); err == nil {
*f = Foo(foo)
}
m := make(map[string]interface{})
if err = json.Unmarshal(bs, &m); err == nil {
delete(m, "a")
delete(m, "b")
f.X = m
}
return err
}
The type _Foo
is necessary to avoid recursion while decoding.
这篇关于解组未知字段的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文