douyinglan2599 2018-04-26 05:31
浏览 50
已采纳

json解组后缺少struct对象的嵌套数组

I ran into some problem with unmarshalling string back to struct object when the object has a nested array of struct objects. I use the following code as a demo for my problem:

The json string is

const myStr = `{
  "name": "test_session1",
  "shared_items:": [
    {
      "id": 0,
      "name": ".aspnet"
    },
    {
      "id": 1,
      "name": ".bash_profile"
    }
  ]
}`

I have two structs as following with Session being the parent and SharedItem being the associated child(ren):

type Session struct {
    ID              uint64           `json:"id"`
    Name            string           `json:"name,omitempty"`
    SharedItems     []SharedItem `json:"shared_items"`
}

type SharedItem struct {
    ID          uint64 `json:"id"`
    Name        string `json:"name"`
}

I tried the following to unmarshal the json string, but it looks like the nested array of SharedItem objects are missing, as I saw sess object has 0 shared items, which is not what I expected.

func main() {
    var sess Session
    if err := json.Unmarshal([]byte(myStr), &sess); err != nil {
        panic(err)
    }
    fmt.Printf("sess name is: %s, and has %d shared items
", sess.Name, len(sess.SharedItems)) // printed: sess name is test_session1, and has 0 shared items
}

Here's the link to my go playground: https://play.golang.org/p/a-y5T3tut6g

  • 写回答

1条回答 默认 最新

  • doujianzhi3358 2018-04-26 05:51
    关注

    Golang Spec for json unmarshal describe it all

    To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

    In the json provided the json object for shared items has : colon in it as we can see it is shared_items: not shared_items which is our json tag

      "shared_items:": [
        {
          "id": 0,
          "name": ".aspnet"
        },
        {
          "id": 1,
          "name": ".bash_profile"
        }
      ]
    

    Either remove : or append into your struct json tag to match the same.

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Session struct {
        Name            string           `json:"name,omitempty"`
        SharedItems     []SharedItem    `json:"shared_items"`
    }
    
    type SharedItem struct {
        ID          uint64 `json:"id"`
        Name        string `json:"name"`
    }
    
    const myStr = `{"name":"test_session1","shared_items":[{"id":0,"name":".aspnet"},{"id":1,"name":".bash_profile"}]}`
    
    func main() {
        var sess Session
    
        if err := json.Unmarshal([]byte(myStr), &sess); err != nil {
            panic(err)
        }
        fmt.Println(sess)
        fmt.Printf("sess name is: %s, and has %d shared items
    ", sess.Name, len(sess.SharedItems))
    }
    

    Playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?