簡體   English   中英

在 Golang Structs 和 Json 之間動態轉換

[英]Converting between Golang Structs and Json Dynamically

我想知道是否有一種方法可以在不使用數組的情況下動態擴展結構中共享相同數據類型的條目數。

例如:

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格式如下:

{MasterBedroom:(所有相關的東西)},{SpareBedroom:(它自己的一套東西)}

此外,這只是一個例子,實際上,它可能是具有 100 個房間的建築物,每個房間都有很多家具,所有家具都需要不同的名稱,但共享結構中定義的相同基本數據。 我正在考慮某種 for 循環,它可能會為用戶擁有的卧室數量取用戶值,並在 json 中動態創建那么多卧室,例如:

{Bedroom1:(所有相關的東西)},{Bedroom2:(它自己的一套東西)}....等

我見過幾個使用地圖的例子,但它們最終打印出來:

地圖[[卧室1:[所有東西]],卧室2:[它的東西]]

這也不能按我需要的方式工作

先感謝您

為了在我給出的示例中進行澄清,您需要能夠在 json 中創建無限數量的房間,而無需在 my house 結構中使用 []bedrooms

這與某些人發布的以 user:Frank 為例的 json marshal 示例不同

之前在這里詢問和回答: 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM