像这样解码 JSON(我无法控制):
{
"states": {
"state": [
{ ...}
]
}
}
进入结构如下:
type Device struct {
States struct{ State []State }
}
var dev Device
我得到一个丑陋的语法来访问状态:
dev.States.State[0]
我希望能够转换对象,这样我就可以做
dev.States[0]
这可以用标签来完成吗(在上面的例子中因为不需要而被省略),或者用另一种方法,或者我是否必须首先解码到一个像上面这样的结构然后手动重新映射到我想要的结构?
最佳答案
您所要做的就是实现 Unmarshaler接口(interface)只是添加了方法 UnmarshalJSON(data []byte) error
并且包含了你在 Unmarshal 之后需要的逻辑;如果你想做逆操作(marshal),只需实现 Marshaler界面。
type State struct {
Name string `json:"name"`
}
type Device struct {
States []State
}
func (dev *Device) UnmarshalJSON(data []byte) error {
// anonymous struct with the real backbone of the json
tmp := struct {
States struct {
State []State `json:"state"`
} `json:"states"`
}{}
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
dev.States = tmp.States.State
return nil
}
关于json - 在go中解码json时调整结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40052543/