首先我要说的是,我在Go世界中还比较新手。
我的目标是读取来自JSON API(我无法控制)的json数据。一切都很顺利,我可以显示接收到的ID和标签。但其中的"fields"字段有点不同,因为它是一个动态数组。
我可以从API接收到这个:
{
"id":"M7DHM98AD2-32E3223F",
"tags": [
{
"id":"9M23X2Z0",
"name":"History"
},
{
"id":"123123123",
"name":"Theory"
}
],
"fields": {
"title":"Title of the item",
"description":"Description of the item"
}
}
或者,我可以只接收description
,而不是title
和description
,或者接收另一个随机对象,如long_title
。返回的对象可能完全不同,并且可以是无限数量的对象。但它始终返回具有键和字符串内容的对象,就像示例中所示。
这是目前我的代码:
type Item struct {
ID string `json:"id"`
Tags []Tag `json:"tags"`
//Fields []Field `json:"fields"`
}
// Tag data from the call
type Tag struct {
ID string `json:"id"`
Name string `json:"name"`
}
// AllEntries gets all entries from the session
func AllEntries() {
resp, _ := client.Get(APIURL)
body, _ := ioutil.ReadAll(resp.Body)
item := new(Item)
_ = json.Unmarshal(body, &item)
fmt.Println(i, "->", item.ID)
}
所以,Item.Fields是动态的,无法预测键名是什么,因此据我所知,没有方法可以为其创建结构体。但是,我对Go还很新手,请问有人能给我一些提示吗?谢谢。