我不知道是否有一种方法来动态地扩展,在一个结构共享相同的数据类型的条目的数量,而无需使用一个数组。
例如:
type MyHouse struct{
Bedroom *Bedroom `json:"bedroom"`
Kitchen *Kitchen `json:"Kitchen"`
}
type Kitchen struct{
Sink *Sink `json:"sink"`
Oven *Oven `json:"oven"`
}
type Oven struct{
Brand string `json:"brand"`
HobSize []int `json:"hobs"`
type Sink struct{
Volume int `json:"volume"`
}
type Bedroom struct{
Bed *Bed `json:"bed"`
Table *Table `json:"table"`
}
type Bed struct{
Brand string `json:"brand"`
Size String `json:"size"`
type Table struct{
Brand string `json:"brand"`
Legs int `json:"legs"`
SurfaceArea int `json:"SurfacceArea"`
Draws []Draws`json:"draws"`
}
type Draws struct{
Depth int `json:"depth"`
Width int `json:"width"`
Length int `json:"length"`
}
func main() {
res := &MyHouse{
Bedroom: &Bedroom{
Bed: &Bed{
Brand: "Sleepy",
Size : "King"},
Table: &Table{
Brand : "TabelY"
Legs : 1
SurfaceAr: 32
Draws : []Draws{
{
Depth :10
Width :10
Length :10
},
{
Depth :20
Width :10
Length :10
}
}
}
}
Kitcken: &Kitchen{
Oven: &Oven{
Brand: "Bake right",
hobs: []int{12,12,24,24}
}
Sink: &Sink{
Volume: 56
}
}
}
restopring, _ := json.Marshal(res)
fmt.Println(string(resprint))
}
这是罚款只是打印出到底是什么在那里,我可以为变量交换硬编码值(我没有,只是为了保持这个简单)如果我想仅仅是能够改变的值。
我希望能够做的就是头也不回的表到表的阵列(实际上是相同的房间),这样我可以打印出一个JSON添加另一个表完全相同的数据(不同的值)的卧室已格式化是这样的:
{主卧:(所有相关的东西)},{备用卧室:(自己的一套东西)}
而且,这仅仅是一个例子,在现实中,这可能是与建筑间的数百每很多家具在结构中定义的所有需要不同的名称,但共享相同的基础数据。我在想for循环某种可能采取多少间卧室用户有用户价值,并动态地创建许多卧室的JSON,如:
{Bedroom1:(所有相关的东西)},{Bedroom2:(自己的一套东西)} ....等
我已经看到了使用地图,但他们最终打印出几个例子:
地图[Bedroom1:所有的东西],Bedroom2:它的东西]
这也没有工作,我需要它的方式
先感谢您
要我给你将需要能够使JSON房间内的无限数量,而不在我的房子结构使用[]卧室的例子阐明
这是不一样的JSON元帅比如有人已经发布有用户:弗兰克作为一个例子
提出和回答之前这里:Converting Go struct to JSON
// Annotate the struct with json tags
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
// ...
foo := &Foo{Number: 123, Title: "Bar"}
f, err := json.Marshal(foo)