【问题标题】:Correct structure for json unmarshaljson unmarshal 的正确结构
【发布时间】:2017-07-24 22:47:34
【问题描述】:

我不知道如何在 golang 中为这个 json 对象构建结构:

{
    "response": [1702487, {
            "uid": 150261846,
            "first_name": "Олег",
            "last_name": "Брейн"
        }, {
            "uid": 53260546,
            "first_name": "Олег",
            "last_name": "Лобацевич"
        }
    ]
}

如您所见,数组和计数也没有键名。

如果你能提供帮助会很高兴

【问题讨论】:

  • 您希望从哪里得到此响应? 1702487 是什么?

标签: arrays json object go


【解决方案1】:

在这种情况下,您将不得不在某处下注并使用 interface{},例如:

    package main

    import (
            "fmt"
            "encoding/json"
    )

    type JsObject struct {
            Response []interface{}
    }

    func main() {
            bs := []byte(`{"response":[1702487,{"uid":150261846,"first_name":"Олег","last_name":"Брейн"},{"uid":53260546,"first_name":"Олег","last_name":"Лобацевич"}]}`)
            var jso JsObject
            json.Unmarshal(bs, &jso)
            fmt.Printf("%+v\n", jso)
    }

【讨论】:

    【解决方案2】:

    Json to go 对于这类事情非常方便:

    https://mholt.github.io/json-to-go/

    如果您可以删除使其成为异构列表的虚假 1702487,您应该能够轻松地将其解析为适当的结构,否则您可能会卡在使用接口:

    https://play.golang.org/p/w7ebLTuOj9

    大概你想要一个这样的结构数组:

    type Person struct {
      UID       int `json:"uid"`
      FirstName string `json:"first_name"`
      LastName  string `json:"last_name"`
    }
    

    不确定 1702487 是什么,但如果是请求的 uid,它实际上并不属于数组。

    【讨论】:

    • 1702487 是该对象中名字与您相同的总人数
    • 你的结构非常好,但是响应仍然有名为“response”的键,所以结构看起来会有所不同。有没有办法删除或跳过键?就像直接跳入 person 对象,忽略“响应”和那个计数
    • 我会清理数组中 int 键的数据(你可以留下 resonse 键)然后使用它。据我所知,另一种方法是使用 map[string]interface{} 手动解析。如果您控制数据,我会更改它以进行解析,而不是您无法清理它。
    【解决方案3】:
    type AutoGenerated struct {
        Response []interface{} `json:"response"`
    }
    

    【讨论】:

    • 请解释这是如何解决问题的。
    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2018-08-06
    • 2020-08-23
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多