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

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

Unmarshaling string with repeated fields into json

问题

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

  1. package main
  2. import "fmt"
  3. import "encoding/json"
  4. func main() {
  5. x := `{
  6. "Header": {
  7. "Encoding-Type": [
  8. "gzip"
  9. ],
  10. "Bytes": [
  11. "29"
  12. ]
  13. }
  14. }`
  15. type HeaderStruct struct {
  16. A string `json:"Encoding-Type"`
  17. B []string `json:"Bytes"`
  18. }
  19. type Foo struct {
  20. Header HeaderStruct `json:"Header"`
  21. }
  22. var f Foo
  23. if e := json.Unmarshal([]byte(x), &f); e != nil {
  24. fmt.Println("Failed:", e)
  25. } else {
  26. fmt.Println("unmarshalled=", f)
  27. }
  28. }

尝试将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?

  1. package main
  2. import "fmt"
  3. import "encoding/json"
  4. func main() {
  5. x := `{
  6. "Header": {
  7. "Encoding-Type": [
  8. "gzip"
  9. ],
  10. "Bytes": [
  11. "29"
  12. ]
  13. }
  14. }`
  15. type HeaderStruct struct {
  16. A string
  17. B []string
  18. }
  19. type Foo struct {
  20. Header HeaderStruct
  21. }
  22. var f Foo
  23. if e := json.Unmarshal([]byte(x), &f); e != nil {
  24. fmt.Println("Failed:", e)
  25. } else {
  26. fmt.Println("unmarshalled=", f)
  27. }
  28. }

答案1

得分: 2

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

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

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

  1. type HeaderStruct struct {
  2. A []string `json:"Encoding-Type"`
  3. B []string `json:"Bytes"
  4. }

答案2

得分: 1

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

  1. type HeaderStruct struct {
  2. Encoding []string `json:"Encoding-Type"`
  3. Bytes []string `json:"Bytes"`
  4. }
英文:

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...

  1. type HeaderStruct struct {
  2. Encoding []string `json:"Encoding-Type"`
  3. Bytes []string `json:"Bytes"
  4. }

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:

确定