douyi7283 2017-02-01 23:52
浏览 138
已采纳

Golang中的Json Unmarshal类型模型

I have a RESTful service that returns response similar to show below:

"Basket" : {
  "Count": 1,
  "Fruits": {[
    {
      "Name":"Mango", 
      "Season":"Summer"
    },
    {
      "Name":"Fig", 
      "Season":"Winter"}
  ]}
}

I am trying to create Go lang model to unmarshal the contents. Following is the code I have tried:

type Response struct {
    Count   int
    Fruits []Fruit
}

type Fruit struct {
    Name string
    Season string
}

But when I marshal the Response object in my test code I don't see similar json. (https://play.golang.org/p/EGKqfbwFvW) Marshalled data always appears as :

{
  "Count":100,
  "Fruits":[
    {"Name":"Mango","Season":"Summer"},
    {"Name":"Fig","Season":"Winter"}
  ]
}

Notice the Fruits appearing as array [] and not {[]} in original json. How can I model structs in golang for this response?

  • 写回答

2条回答 默认 最新

  • doushijiao0679 2017-02-02 14:43
    关注

    Your model is totally correct and valid, but the JSON object is not. "Fruits" doesn't have name if it should be key value pair or it should be wrapped in [] not {}.

    JSON obj should be formatted like this:

    {
      "Basket" : {
        "Count": 1,
        "Fruits": [
          {
            "Name":"Mango", 
            "Season":"Summer"
          },
          {
            "Name":"Fig", 
            "Season":"Winter"
          }
        ]
      }
    }
    

    And actually invalid json shouldn't work https://play.golang.org/p/yoW7t4NfI7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dsfg3241 2017-02-02 01:04
    关注

    I would make 'Baskets' a struct within 'Response', create a 'BasketsData' struct, and give it all some labels.

    type Fruit struct {
        Name   string `json:"Name"`
        Season string `json:"Season"`
    }
    
    type BasketData struct {
        Count  int     `json:"Count"`
        Fruits []Fruit `json:"Fruits"`
    }
    
    type Response struct {
        Basket BasketData `json:"Basket"`
    }
    

    This way you will get a top level JSON response when you marshall it.

    fruitmania := []Fruit{{Name: "Mango", Season: "Summer"},
                           {Name: "Fig", Season: "Winter"}}
    basket := Response{BasketData{Count: 100, Fruits: fruitmania}}
    
    b, _ := json.Marshal(basket)
    fmt.Println(string(b))
    

    checkit-checkit out: https://play.golang.org/p/TuUwBLs_Ql

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在工控机(Ubuntu系统)上外接USB蓝牙硬件进行蓝牙通信
  • ¥15 关于PROCEDURE和FUNCTION的问题
  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
  • ¥15 C语言除0问题的检测方法
  • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
  • ¥15 macos13下 ios交叉编译的问题
  • ¥15 bgz压缩文件怎么打开
  • ¥15 封装dll(引入了pcl的点云设计库)
  • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发