dpthuyh1678 2017-04-01 18:33
浏览 20
已采纳

定制Json Marshaling

I have a third-party json api to work with in go.
It has some endpoints which return data as key-value.
For example here is json for statuses:

{
  "result": {
    "0": "done",
    "1": "incomplete",
    "2": "completed",
    ....
  }
}

So as you see it is not an array it is an object.
Is it possible to marshal this kind of json to array of objects like

type Status struct {
    Id int
    Status string
}

without using additional struct like

type StatusReposne struct {
    Result map[string]string `json:"result"`
}

and code to extract values?

  • 写回答

1条回答 默认 最新

  • dtr32221 2017-04-01 20:49
    关注

    As @mkopriva stated in the comment, it's not possible with some extra work. This code does provide means to Marshal/Unmarshal data to/from a slice of Statuss:

    func main() {
        sr := new(StatusReposne)
    
        json.Unmarshal([]byte(input), sr)
        fmt.Printf("%+v
    ", sr)
    
        js, _ := json.Marshal(sr)
        fmt.Printf("%s
    ", js)
    }
    
    type StatusReposne struct {
        Result []Status `json:"result"`
    }
    
    type Status struct {
        Id     int
        Status string
    }
    
    func (x *StatusReposne) MarshalJSON() ([]byte, error) {
        var buffer struct {
            Result map[string]string `json:"result"`
        }
        buffer.Result = make(map[string]string)
        for _, v := range x.Result {
            buffer.Result[strconv.Itoa(v.Id)] = v.Status
        }
        return json.Marshal(&buffer)
    }
    
    func (x *StatusReposne) UnmarshalJSON(b []byte) error {
        var buffer struct {
            Result map[string]string `json:"result"`
        }
        buffer.Result = make(map[string]string)
        json.Unmarshal(b, &buffer)
        for k, v := range buffer.Result {
            k, _ := strconv.Atoi(k)
            x.Result = append(x.Result, Status{Id: k, Status: v})
        }
        return nil
    }
    
    var input = `{
      "result": {
        "0": "done",
        "1": "incomplete",
        "2": "completed"
      }
    }`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用