英文:
Define structure in golang
问题
我正在进行一个项目,其中我以以下格式接收有效载荷数据:
"name":"John",
"date":"2022-04-14",
"price":200,
"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]
我应该如何定义这个结构体?如果你知道,请告诉我。谢谢!
英文:
I am working on a project in which I receive payload data in the following format:
"name":"John",
"date":"2022-04-14",
"price":200,
"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]
How should I define the struct for this? If you know please let me know. Thanks!
答案1
得分: 2
这部分代码看起来像这样:
type XXX struct {
Dependencies []map[string]Dependency `json:"dependencies"`
}
type Dependency struct {
Items []int `json:"items"`
Pricing []int `json:"pricing"`
}
但我不确定element_x是否是动态的。如果它是预定义的,那就没问题。
英文:
This part
"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]
Looks like
type XXX struct {
Dependencies []map[string]Dependency `json:"dependencies"`
}
type Dependency struct {
Items []int // json…
Pricing []int // json…
}
But I am not sure… if element_x is dynamic or not. If it is predefined, ok.
答案2
得分: 1
如果你的JSON是这样的:
{
"name": "John",
"date": "2022-04-14",
"price": 200,
"dependencies": [
{
"element_1": {
"items": [2, 4],
"pricing": [1, 2]
}
},
{
"element_2": {
"items": [5, 4],
"pricing": [1, 6]
}
}
]
}
那么你可以创建如下的结构体:
type DemoStruct struct {
Name string `json:"name"`
Date string `json:"date"`
Price int64 `json:"price"`
Dependencies []Dependency `json:"dependencies"`
}
type Dependency struct {
Element1 *Element `json:"element_1,omitempty"`
Element2 *Element `json:"element_2,omitempty"`
}
type Element struct {
Items []int64 `json:"items"`
Pricing []int64 `json:"pricing"`
}
英文:
If your json is
{
"name": "John",
"date": "2022-04-14",
"price": 200,
"dependencies":
[
{
"element_1":
{
"items":
[
2,
4
],
"pricing":
[
1,
2
]
}
},
{
"element_2":
{
"items":
[
5,
4
],
"pricing":
[
1,
6
]
}
}
]
}
Then you can create struct like this
type DemoStruct struct {
Name string `json:"name"`
Date string `json:"date"`
Price int64 `json:"price"`
Dependencies []Dependency `json:"dependencies"`
}
type Dependency struct {
Element1 *Element `json:"element_1,omitempty"`
Element2 *Element `json:"element_2,omitempty"`
}
type Element struct {
Items []int64 `json:"items"`
Pricing []int64 `json:"pricing"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论