doutang7383 2016-10-14 21:52
浏览 21
已采纳

在Go中解组json时调整结构

Unmarshalling JSON (that I do not control) like this:

{
    "states": {
        "state": [
            { ...}
        ]
    }
}

into a struct like:

type Device struct {
    States    struct{ State []State }
}
var dev Device

I get an ugly syntax to access a state:

dev.States.State[0]

I would like to be able to transform the object so I can do

dev.States[0]

Can this be done with tags (omitted in the above example because not needed), or with another method, or do I have to first unmarshal to a struct like the above then manually remap to a struct as I want it?

  • 写回答

1条回答 默认 最新

  • dryift6733 2016-10-14 22:25
    关注

    All you have to do is implement the Unmarshaler interface just adding the method UnmarshalJSON(data []byte) error and including the logic that you need after Unmarshal; and if you want to do the inverse operation(marshal) just implement the Marshaler interface.

    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
    }
    

    Full example: https://play.golang.org/p/gNpS13ED_i

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看