Go json and embedded struct


使用 embedded struct 做 json 的 marshal 跟 unmarshal 時,json 欄位會省略 struct embedded 欄位的中間名,以比較簡潔的形式呈現。如果 struct 有寫出欄位名稱,json 欄位就會多那一層。

使用 embedded struct

type Serving struct {
    Amount float64
    Unit   string
}

type Food struct {
    Name string
    Serving    // embedded struct
    NutritionInfo
    Comment string
}

marshal 結果:

{
  "Name":"Banana",
  "Amount":100,
  "Unit":"g",
  "Calorie":0,
  "Carb":0,
  "Fat":0,
  "Protein":0,
  "Comment":""
}

不使用 embedded struct

type Food struct {
    Name string
    Serving Serving    // not embedded struct
    NutritionInfo
    Comment string
}

marshal 結果:

{
  "Name":"Banana",
  "Serving":
  {
    "Amount":100,
    "Unit":"g"
  },
  "Calorie":0,
  "Carb":0,
  "Fat":0,
  "Protein":0,
  "Comment":""
}

不用 embeded struct 就會有一層 Serving,用 embedded struct 就會省略 Serving 這層。

#GO






你可能感興趣的文章

Day02: GraphQL and GitHub GraphQL - Handling Data

Day02: GraphQL and GitHub GraphQL - Handling Data

JavaScript 實作 Array Shuffle

JavaScript 實作 Array Shuffle

This is shell script for example code

This is shell script for example code






留言討論