我不习惯golang
。
当我请求时,我得到了以下日志。
我想解析日志并存储到struct
类型。
有人告诉我该怎么做吗?
提前致谢。
例如:
type ResultStruct struct{
id int
guid string
name string
}
for k, v := range data {
fmt.Print(v.id) fmt.Print(v.guid) fmt.Print(v.name)
}
[日志]
data: [map[id:90001 guid:a name:test1] map[guid:b name:test2 id:90002] map[name:test3 id:90003 guid:c]]
[来源]
response := httpClient.Do(request)
var data interface{}
rawdata, err := ioutil.ReadAll(response.body)
json.Unmarshal(rawdata, &data)
fmt.Println("data :", data)
最佳答案
这是 Go 新手常犯的错误。
由于语言设计,json.Unmarshal
只能编码到 exported 中字段。
只需将每个字段名称的首字母大写即可将其导出。您可以选择添加字段标签来告诉 json.Marshal 使用什么键名。仅当您要使用 json.Marshal
时才需要。
type ResultStruct struct{
Id int `json:"id"`
Guid string `json:"guid"`
Name string `json:"name"`
}
To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. Unmarshal will only set exported fields of the struct.
关于json - golang 类型转换。接口(interface)结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598102/