编组到 JSON 结构扩展了另一个具有相同字段标签的结构
Marshal to JSON struct extended another struct with the same field label
- 我有 2 个
struct
包含一个具有相同标签 (id
) 和相同 JSON 注释的字段 (`json:"id"` ).
- 一个
struct
(Bar
) 包含来自另一个 struct
(Foo
) 的字段标签及其值。
我想 JSON 使用两个 id
字段编组包装器 struct
Bar
,但内部的 JSON 注释(例如`json:"foo_id"`)。我找不到办法,但看起来应该可行?
快速浏览这里https://golang.org/pkg/encoding/json/我找不到解决方案。
有可能吗?有什么解决办法吗?
我试图避免结构之间所有 get/set 到 copy/paste 值的样板,我希望这是可行的。
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
ID int `json:"id"`
Stuff string `json:"stuff"`
}
type Bar struct {
ID int `json:"id"`
Foo
// the following does not work,
// I've tried a few variations with no luck so far
// Foo.ID int `json:"foo_id"`
OtherStuff string `json:"other_stuff"`
}
func main() {
foo := Foo{ID: 123, Stuff: "abc" }
bar := Bar{ID: 456, OtherStuff: "xyz", Foo: foo }
fooJsonStr, _ := json.Marshal(foo)
barJsonStr, _ := json.Marshal(bar)
fmt.Printf("Foo: %s\n", fooJsonStr)
fmt.Printf("Bar: %s\n", barJsonStr)
}
给出这个输出:
Foo: {"id":123,"stuff":"abc"}
Bar: {"id":456,"stuff":"abc","other_stuff":"xyz"}
One struct (Bar) inherit from the other struct (Foo).
显然不是,因为 Go 中没有继承。
如果要将Foo的ID命名为foo_id:
type Foo struct {
ID int `json:"foo_id"`
Stuff string `json:"stuff"`
}
非常简单。
- 我有 2 个
struct
包含一个具有相同标签 (id
) 和相同 JSON 注释的字段 (`json:"id"` ). - 一个
struct
(Bar
) 包含来自另一个struct
(Foo
) 的字段标签及其值。
我想 JSON 使用两个 id
字段编组包装器 struct
Bar
,但内部的 JSON 注释(例如`json:"foo_id"`)。我找不到办法,但看起来应该可行?
快速浏览这里https://golang.org/pkg/encoding/json/我找不到解决方案。
有可能吗?有什么解决办法吗? 我试图避免结构之间所有 get/set 到 copy/paste 值的样板,我希望这是可行的。
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
ID int `json:"id"`
Stuff string `json:"stuff"`
}
type Bar struct {
ID int `json:"id"`
Foo
// the following does not work,
// I've tried a few variations with no luck so far
// Foo.ID int `json:"foo_id"`
OtherStuff string `json:"other_stuff"`
}
func main() {
foo := Foo{ID: 123, Stuff: "abc" }
bar := Bar{ID: 456, OtherStuff: "xyz", Foo: foo }
fooJsonStr, _ := json.Marshal(foo)
barJsonStr, _ := json.Marshal(bar)
fmt.Printf("Foo: %s\n", fooJsonStr)
fmt.Printf("Bar: %s\n", barJsonStr)
}
给出这个输出:
Foo: {"id":123,"stuff":"abc"}
Bar: {"id":456,"stuff":"abc","other_stuff":"xyz"}
One struct (Bar) inherit from the other struct (Foo).
显然不是,因为 Go 中没有继承。
如果要将Foo的ID命名为foo_id:
type Foo struct {
ID int `json:"foo_id"`
Stuff string `json:"stuff"`
}
非常简单。