json - 将具有重复字段的字符串解码为 json

标签 json go

尝试将字符串解码为 json,但我的结构定义不起作用。如何修复?

package main

import "fmt"
import "encoding/json"

func main() {
    x := `{
    "Header": {
        "Encoding-Type": [
            "gzip"
        ],
        "Bytes": [
            "29"
        ]
    }
}`

    type HeaderStruct struct {
        A string
        B []string
    }
    type Foo struct {
        Header HeaderStruct
    }


    var f Foo 
    if e := json.Unmarshal([]byte(x), &f); e != nil {
        fmt.Println("Failed:", e)
    } else {
        fmt.Println("unmarshalled=", f)
    }

}

最佳答案

您的变量名称与 json 键的名称不匹配,并且它们都是 []string。你可以做

type HeaderStruct struct {
    A []string `json:"Encoding-Type"`
    B []string `json:"Bytes"
}

关于json - 将具有重复字段的字符串解码为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260877/

相关文章:

json - Flutter 使用来自 Golang RFC3339 的 DateTime 解析 json : FormatException: Invalid date format

go - 如何获取 IMAP 消息的可见/不可见状态

json - 匹配模式后提取子串

javascript - 不知道为什么这个 JavaScript 函数不起作用

去死锁所有 goroutines 睡着了

go - 使用 Echo 框架在 Golang 中安装 SSL 证书时出现问题(客户端向 HTTPS 服务器发送了 HTTP 请求。)

api - 如何使用相同的端口地址和不同的句柄模式同时提供网页和 API 路由

javascript - 使用lodash过滤json数组中具有多个键的多个值

java - 使用 Java 对 Json 对象数组进行模式验证

javascript - 如何在 Node.js 中过滤 JSON 数据