如何在golang中为变量json响应映射或制作结构? [英] How to map or make struct for variable json response in golang?
问题描述
我正在调用 API 并获取 json,但不知道如何为响应创建结构体我使用 JSON-to-GO 来获取响应结构体.但问题是每次的反应都不一样.例如,我有一个使用 JSON-to-GO 的结构:-
I am calling an API and getting json and don't know how to make a struct for the response I have used JSON-to-GO to get a struct for the response. But the problem is the response is not same every time. For example I have a struct using the JSON-to-GO :-
type Autogenerated struct {
Response struct {
Results struct {
Status string `json:"status"`
StatusCode int `json:"status_code"`
ResultsData struct {
ResultsCount int `json:"results_count"`
NearbyCount int `json:"nearby_count"`
} `json:"results_data"`
SortData struct {
SortBy string `json:"sort_by"`
} `json:"sort_data"`
ResponseData struct {
Data0 struct {
Name string `json:"name"`
} `json:"data_0"`
Data1 struct {
Name string `json:"name"`
} `json:"data_1"`
} `json:"response_data"`
Time float64 `json:"time"`
} `json:"results"`
} `json:"response"`
}
Data1 和 Data0 可以更像 Data2、Data3....,我希望 Name 位于 Data0、Data1 ....我对 golang 很陌生,也许我们可以使用 Map 但由于一直不一样,我不知道该怎么做.还有很多与姓名一起提交的文件,我没有在这里粘贴以保持问题的清晰.
The Data1 and Data0 can be any more like Data2, Data3.... and I want the Name inside of the Data0, Data1 .... I am very new to golang, Maybe we can use Map for it but due to being not same all the time I don't know, how to do it. Also there are a lot of filed along with Name which I have not pasted here to keep the question clean.
推荐答案
使用 map[string]interface{}
作为响应数据类型.Data0 到任意数字 os Data0 类型字段解组以映射为键 data_0, data_1, data_2
use map[string]interface{}
for Response data type. Data0 to any number os Data0 type fields unmarshal to map as keys data_0, data_1, data_2
ResponseData map[string]interface{} `json:"response_data"`
如果您的数据作为每个 data_0 ... data_n 的相同对象出现,则定义如下结构类型并使用该类型定义映射.
If your Data coming as a same object for every data_0 ... data_n, then define struct type like below and define map with that type.
//new data type
type Data struct {
Name string `json:"name"`
}
//add this to your Autogenerated struct
ResponseData map[string]Data `json:"response_data"`
或简单地添加
ResponseData map[string]struct{
Name string `json:"name"`
} `json:"response_data"`
这篇关于如何在golang中为变量json响应映射或制作结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!