gpt4 book ai didi

json - 如何使用 goreq 接收复杂的 json?

转载 作者:IT王子 更新时间:2023-10-29 02:02:45 25 4
gpt4 key购买 nike

我是 Go 的初学者,我正在尝试调用一个 json rest-API,我正在尝试为其使用 goreq request lib .在自述文件中它给出了 the following example用于解码接收到的 json:

type Item struct {
Id int
Name string
}

var item Item

res.Body.FromJsonTo(&item)

我理解这个例子,但我收到的 json 更复杂(见下文)。我不确定如何创建代表这种复杂结构的 struct。我可以将它写在一个 struct 中吗,或者我是否需要为 bid 和 ask 数组使用映射,为 bid 和 ask 对象使用另一个结构,为 "vars 使用另一个结构" 对象?

难道没有任何自动json_to_struct() 函数可以在接收到 json 时动态构建结构(我看过但找不到任何东西)?

欢迎所有提示!

{
"success": true,
"message": "something",
"vars": {"some": "value", "thenumber": 7612.32},
"result": {
"bids": [
{"quantity": 2, "price": 416.02, "cm": "some text"},
etc..
],
"asks": [
{"quantity": 1, "price": 420.02, "cm": "some text"},
etc..
],
"slip": 4
}
}

最佳答案

长话短说

Can I write it in one struct

or do I need to use maps for the bid and ask arrays, and yet another struct for the bid and ask objects?

在我真正做这里的牵手之前,我建议您实际花更多的时间来习惯 Go 中的做事方式。这可能是一项繁琐的工作,但它非常简单。

长版

I'm not sure how I would create a struct which represents this complex structure.

如果您只需要在您的程序中表示它,而无需任何 JSON,您将采用相同的方式。

在我们将其翻译成 Go 之前,让我们用英语解释您在该消息中的内容:

你有一个包含字段的结构:

  • 成功 - bool 值
  • 消息 - 字符串
  • 结果 - 结构

现在,Result 也是一个结构体,所以我们需要描述它:

  • 出价 - 结构数组
  • 询问 - 结构数组
  • 滑动 - 整数

让我们对出价和要价做同样的事情(看起来一样所以我会节省空间)

  • 数量 - 整数
  • 价格 - Float64
  • Cm - 字符串

现在让我们定义我们的结构:

我们称容器结构为“Response”,结果为“Result”

type Response struct {
Success bool `json:"success"`
Message string `json:"message"`
Result Result `json:"result"`
}

type Result struct {
Bids []Quote `json:"bids"`
Asks []Quote `json:"asks"`
Slip int `json:"slip"`
}

type Quote struct {
//As asks and bids are have the same structure we can save code
Quantity int `json:"quantity"`
Price float64 `json:"price"`
Cm string `json:"cm"`
}

不要忘记添加注释,以便 (Un)Marshaling 函数可以将 JSON 中的字段正确匹配到结构。

我相信以上是实现这一点的最佳且更易于维护的方法,但是您也可以编写与嵌套匿名结构相同的结构:

type Response struct {
Success bool `json:"success"`
Message string `json:"message"`
Result struct {
Bids []struct {
Quantity int `json:"quantity"`
Price float64 `json:"price"`
Cm string `json:"cm"`
} `json:"bids"`
Asks []struct {
Quantity int `json:"quantity"`
Price float64 `json:"price"`
Cm string `json:"cm"`
} `json:"asks"`
Slip int `json:"slip"`
} `json:"result"`
}

顺便说一句,几周前我发现了一个有趣的工具,它可以自动将 JSON 转换为您可以立即在代码中声明的 Go 结构:https://transform.now.sh/json-to-go/

关于json - 如何使用 goreq 接收复杂的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46295450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com