json - golang 类型转换。接口(interface)结构

标签 json go unmarshalling

我不习惯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"`
}

引用encoding/json package :

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/

相关文章:

javascript - 将 JSON 从索引操作提供给公共(public)文件夹中的 index.html

go - 获取Go中前3个月的首个和最后一个日期

xml - Golang 将 XML 属性解码到接口(interface)中

json - 无法将外部结构直接调用到 map[string]struct

java - 如何在 Camel route 使用java boolean 条件?

javascript - 通过 AJAX 或 PHP 将 JavaScript 数据写入 JSON 文件

ios - 将 JSOn 绘制到 UITableviewCell 时出错

json - 如何在时代更新 Postgres 中的当前时间的 json 对象

go - $GOPATH 的最佳位置在哪里?

xml - 获取 xml 节点属性的值