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 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并