golang 中的 Json 解码类型模型

标签 json go struct marshalling unmarshalling

我有一个 RESTful 服务,返回类似于下面显示的响应:

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

我正在尝试创建 Go 语言模型来解码内容。以下是我试过的代码:

type Response struct {
    Count   int
    Fruits []Fruit
}

type Fruit struct {
    Name string
    Season string
}

但是当我在我的测试代码中编码 Response 对象时,我没有看到类似的 json。 ( https://play.golang.org/p/EGKqfbwFvW ) 编码数据始终显示为:

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

请注意 Fruits 在原始 json 中显示为数组 [] 而不是 {[]}。我如何在 golang 中为这个响应建模结构?

最佳答案

您的模型是完全正确和有效的,但 JSON 对象不是。 "Fruits"如果它应该是键值对或者应该包含在 [] 中,则没有名称不是{} .

JSON obj 的格式应该是这样的:

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

实际上无效的 json 不应该工作 https://play.golang.org/p/yoW7t4NfI7

关于golang 中的 Json 解码类型模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992035/

相关文章:

json - Go语言中带有结果对象的动态结构

c - 将不同的结构成员设置为彼此相等

javascript - 从浏览器向 Arduino 发送请求具有高延迟

javascript - 将 JSON 中的键小写 - Node JS

java - Golang 的 WaitGroup 的 Java 等价物是什么

我可以为一个 union 成员分配一个值并从另一个 union 成员那里读取相同的值吗?

c - 指向结构体指针的指针

ios - Swift:Mandrill POST 问题

java - 用 jackson 序列化日期列表

go - 最重要的测试用例