英文:
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)
}
}
尝试将A
和B
字段的标签添加到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"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论