解析动态json对象 [英] Parse dynamic json object
本文介绍了解析动态json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何解析此json对象:
How can I parse this json object:
{
"ports": {
"0": {
"3306": "3306"
},
"1": {
"3307": "9908"
}
}
}
我可以有N个端口,每个端口的值始终是key:value对.
I can have N ports, and the values for each port will always be a key:value pair.
到目前为止,我已经尝试过:
So far I've tried this:
type Ports struct {
Port map[string]string
}
这样我得到了键(0、1),但是值是空的.
With this I get the keys (0, 1) but the values are empty.
我也尝试过:
type Ports struct {
Port map[string]struct{
Values map[string]string
}
}
但也不起作用.
这就是我解码json对象的方式:
This is how I am decoding the json object:
var requestBody Ports
decoder := json.NewDecoder(body)
err := decoder.Decode(&requestBody)
推荐答案
使用此类型:
type Ports struct {
Ports map[string]map[string]string
}
注意:
- 字段名称非常匹配.我使用字段名称端口"来匹配JSON文本中使用的名称.
- Go类型在JSON中应具有相同级别的嵌套.一个结构和映射每个计数用于一个嵌套级别.第一次尝试没有足够的嵌套,第二次尝试具有太多的嵌套级别(带有值"字段的结构).
这篇关于解析动态json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文