将具有重复字段的字符串解组为 JSON

huangapple go评论78阅读模式
英文:

Unmarshaling string with repeated fields into json

问题

尝试将字符串解组为JSON,但我的结构定义无法工作。如何修复它?

package main

import "fmt"
import "encoding/json"

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

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

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

尝试将AB字段的标签添加到HeaderStruct结构体中的字段上,以指定JSON中的字段名称。这样,json.Unmarshal函数将能够正确地将JSON字符串解组到结构体中。

英文:

Trying to unmarshal a string into json, but my struct definitions don't work. How can it be fixed?

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)
	}

}

答案1

得分: 2

你的变量名与 JSON 键的名称不匹配,且它们都是 []string 类型。你可以这样做:

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

The names of your variables don't match the names of the json keys and both of them are []string. You can do

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

答案2

得分: 1

你需要使用 JSON 注解来告诉解组器数据应该放在哪里,另外你的模型中的 A 类型是错误的,它也应该是一个数组。我还会将你字段的名称更改为有意义的内容...

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

You need json annotations to tell the unmarshaller which data goes where, also the type of A in your model is wrong, it should also be an array. I'm also going to change the names of your fields to something meaningful...

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

huangapple
  • 本文由 发表于 2015年8月28日 07:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/32260877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定