json - 使用数组中包含的 [int] 字符串映射解码 JSON

标签 json go

我试图将以下 JSON 解码为一个结构,但我无法用 [[int,string]] 翻译值字段的内容 这是我到目前为止所拥有的:

type Response struct {
            Metric struct {
                Name string `json:"name,omitempty"`
                Appname string `json:"appname,omitempty"`
            } `json:"metric,omitempty"`
            Values []map[int]string `json:"values,omitempty"`
}

JSON 文件:

{
   "metric":{
      "name":"x444",
      "appname":"cc-14-471s6"
   },
   "values":[
      [
         1508315264,
         "0.0012116165566900816"
      ],
      [
         1508315274,
         "0.0011871631158857396"
      ]
   ]
}

最佳答案

您显示的数据应解码为:

type Response struct {
            Metric struct {
                Name string `json:"name,omitempty"`
                Appname string `json:"appname,omitempty"`
            } `json:"metric,omitempty"`
            Values [][]interface{} `json:"values,omitempty"`
}

如果你想将它传输到 map 实现 json.Unmarshaller 接口(interface) - https://golang.org/pkg/encoding/json/#Unmarshaler

你可以有这样的东西:

type Item struct {
    Key int
    Val string
}
func(item *Item) UnmarshalJSON([]byte) error {
    // TODO: implement 
}

type Response struct {
            Metric struct {
                Name string `json:"name,omitempty"`
                Appname string `json:"appname,omitempty"`
            } `json:"metric,omitempty"`
            Values []Item  `json:"values,omitempty"`
}

关于json - 使用数组中包含的 [int] 字符串映射解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46811235/

相关文章:

go - http.ServeFile () - 客户端文件名问题

go - 如何使用本地包部署Go应用

GoYAML 结构 slice

google-app-engine - GAE Go — 如何使用 GetMulti 与不存在的实体键?

ios - 什么情况下JSONSerialization.data(withJSONObject :) throw a catchable error?

javascript - 在javascript中将Json时间戳转换为正常日期和时间

json - 将复杂的 json 解码为复杂的数据结构在一个子结构上失败

javascript - Vuejs 从数据属性返回 [object Object]

python - urllib2 和 json

java - 如何在没有 JSP 的情况下使用 TOMCAT 和 Jackson 在 SPRING MVC 中将 POJO 转换为 JSON?