在Golang中反序列化图案化的字段

时间:2016-01-29 19:20:59

标签: json go deserialization

我正在编写golang结构,它与一些json结构兼容。但是,大多数字段都知道,json定义中的某些特定模式(如“x- {randomName}”)之后会有很少的字段,我也希望将其反序列化为某个字段{{1}也是。

有没有下降的方法来实现它?

1 个答案:

答案 0 :(得分:1)

效率较低,但您可以解组两次以避免手动映射字段。一旦将所有正确标记的字段放入结构中,然后再次放入map[string]interface{}以获取其他所有内容。如果您不关心重复字段,则甚至不需要过滤第二个地图。

您甚至可以使用UnmarshalJSON方法自动填充结构

type S struct {
    A   string `json:"a"`
    B   string `json:"b"`
    All map[string]interface{}
}

func (s *S) UnmarshalJSON(b []byte) error {
    // create a new type to hide the UnmarshalJSON method
    // otherwise we'll recurse indefinitely.
    type ss S

    err := json.Unmarshal(b, (*ss)(s))
    if err != nil {
        return err
    }
    // now unmarshal again into the All map
    err = json.Unmarshal(b, &s.All)
    if err != nil {
        return err
    }

    return nil
}

http://play.golang.org/p/VBVlRjNlHy