[英]Parse json array into list of struct golang
我有一個 json 如下所示,我正在嘗試為 json 以下的結構創建一個結構,當我解組它時可以為我存儲數據。
{
"clientMetrics": [
{
"clientId": 951231,
"customerData": {
"Process": [
"ABC"
],
"Mat": [
"KKK"
]
},
"legCustomer": [
8773
]
},
{
"clientId": 1234,
"legCustomer": [
8789
]
},
{
"clientId": 3435,
"otherIds": [
4,
32,
19
],
"legCustomer": [
10005
]
},
{
"clientId": 9981,
"catId": 8,
"legCustomer": [
13769
]
},
{
"clientId": 12124,
"otherIds": [
33,
29
],
"legCustomer": [
12815
]
},
{
"clientId": 8712,
"customerData": {
"Process": [
"College"
]
},
"legCustomer": [
951
]
},
{
"clientId": 23214,
"legCustomer": [
12724,
12727
]
},
{
"clientId": 119812,
"catId": 8,
"legCustomer": [
14519
]
},
{
"clientId": 22315,
"otherIds": [
32
],
"legCustomer": [
12725,
13993
]
},
{
"clientId": 765121,
"catId": 8,
"legCustomer": [
14523
]
}
]
}
clientMetrics
是一個 json 數組,其中包含每個clientMetric
object。 每個clientMetric
object 都可以包含各種字段。 我嘗試了類似下面的方法,但我對如何添加 rest 感到困惑,因為我來自 Java 背景,我沒有看到 golang 中有可用的設置。 也對如何添加customerData
object 感到困惑。
type ClientMetrics struct {
ClientId int64
CatId int64
}
將 json 以上解組為 golang 中的ClientMetrics
結構列表的最佳方法是什么?
您可以在此處使用json to go
: https://mholt.ZBF215181B5146052-21347B3D4
但它會重復CustomerData
結構兩次,確保您應該刪除其中一個。
我為您的場景創建了一個示例結構,如下所示:
type AutoGenerated struct {
ClientMetrics []struct {
ClientID int `json:"clientId"`
CustomerData struct {
Process []string `json:"Process"`
Mat []string `json:"Mat"`
} `json:"customerData,omitempty"`
LegCustomer []int `json:"legCustomer"`
OtherIds []int `json:"otherIds,omitempty"`
CatID int `json:"catId,omitempty"`
} `json:"clientMetrics"`
}
您可以在 go 操場上運行它: https://go.dev/play/p/R1M1HfzpEny
如果你使用 VS Code,有一些擴展可以完成這項工作。 其中之一被命名為Paste JSON as Code
。
Paste JSON as code
如果這對您不起作用,您可以隨時使用此站點https://mholt.github.io/json-to-go/但最好使用取消選擇Inline type definitions
選項后獲得的結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.