duanliao6077 2015-06-25 22:48
浏览 318

在Golang中将多个JSON字段解码为一个

I am working with an API that, frustratingly, has field names that vary for the same value. For example, one API response could look like this:

{
  "PersonFirstName": "John",
  "PersonLastName": "Smith"
}

while another looks like this:

{
  "FirstNm": "John",
  "LastNm": "Smith"
}

Suppose then I had a struct which I would like to decode my JSON to. It might look like this:

type Name struct {
    FirstName string
    LastName  string
}

Typically I would just be able to do the following if the API was consistent:

type Name struct {
    FirstName string `json:"PersonFirstName"`
    LastName  string `json:"PersonLastName"`
}

and then use the built-in JSON decoder to build the struct. When there are multiple field values like this, though, I don't know a clean way to decode the JSON into a struct. Any ideas?

  • 写回答

1条回答 默认 最新

  • duanpengya7074 2015-06-25 22:51
    关注

    Use a map[string]string. That is the equivalent structure in Go. You're looking at those as being structs because their objects, and that's the sensible thing to do. Anytime you see different values for the property names that's your clue that a map is the only reasonable representation of the data in Go.

    If you need to normalize/have static typing implement a helper function called NameFromMap(data map[string]string) (*Name, error). Put the switch statement in there to deal with the various values you can have for the keys.

    Edit: you could also implement UnmarshalJSON for your type. You would just put this switch statement I allude to there. Here's an example; How do I Unmarshal JSON?

    I personally prefer the first method I said because this sort of abstracts a step that I'd rather see called explicitly.

    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料