我正在编写一个端点来为 Geckoboard 返回数据,它的格式除外:
{
"item": [
{
"value": "274057"
},
[
"38594",
"39957",
"35316",
"35913",
"36668",
"45660",
"41949"
]
]
}
“item”
是一个不同结构的数组。我将如何在 Go 中表示这些数据?
注意:这与我如何解码无关,我需要生成这种格式。
最佳答案
这东西比您想象的要容易。对于普通读者来说,它只是没有很好的记录。我会推荐 ffjson
而不是普通的 json
。它的组成方式使您无需更改库名称以外的语法。
就这么简单:
type User struct {
Id int `json:'id'`
Name string `json:name`
SomeId1 int `json:some_id_1`
SomeId2 int `json:some_id_2`
SomeId3 int `json:some_id_3`
SomeId4 int `json:some_id_4`
}
item := map[string]User{}
for i := 0; i < 10; i++ {
item[strconv.itoa(i)] = User{i, "Username X", 38393, 29384, 12393, 123981}
}
buf, err := ffjson.Marshal(&item)
结构的缺点(即使在 ffjson
中仍然如此)是 reflection
将始终被使用,在您需要高性能的时候,您会浪费很多CPU周期。 ffjson
比普通 json
快 2-3 倍,当您将其保留在 map 上时。通过这种方式,库可以编译您编码的每个数据结构并重新使用它,而不是不断地使用 reflect
检查数据完整性/结构。
关于json - 在 Go 中表示此 JSON 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30214094/