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"
}
Run Code Online (Sandbox Code Playgroud)
while another looks like this:
{
"FirstNm": "John",
"LastNm": "Smith"
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
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"`
}
Run Code Online (Sandbox Code Playgroud)
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?
用一个map[string]string。这是 Go 中的等效结构。您将它们视为结构,因为它们是对象,这是明智的做法。每当你看到属性名称的不同值时,这就是你的线索:映射是 Go 中数据的唯一合理表示。
如果您需要标准化/静态类型,请实现一个名为 的辅助函数NameFromMap(data map[string]string) (*Name, error)。将 switch 语句放在那里来处理键可以拥有的各种值。
编辑:您也可以UnmarshalJSON针对您的类型实现。您只需将我提到的这个 switch 语句放在那里即可。这是一个例子;如何解组 JSON?
我个人更喜欢我所说的第一种方法,因为这种抽象了我宁愿看到显式调用的步骤。
| 归档时间: |
|
| 查看次数: |
1539 次 |
| 最近记录: |