type Struct struct {
Value string `json:"value"`
Value1 string `json:"value_one"`
Nest Nested `json:"nest"`
}
type Nested struct {
Something string `json:"something"`
}
我想添加不在 struct 定义中的元素,而不创建另一个 struct 类型.例如
Struct.Extra1 = Nested{"yy"}
Struct.Nested.Extra2 = "zz"
结果会怎样
{
"Value": "xx",
"Value1": "xx",
"Extra1": {
"Something", "yy"
},
"Nest": {
"Something": "xx",
"Extra2": "zz"
}
}
SOLUTION1:
我想添加omitempty
来实现这一点,但是这会使 struct 变得复杂.
type Struct struct {
Value string
Value1 string
Nest Nested
Extra1 Nested `json:"omitempty"`
}
type Nested struct {
Something string
Extra2 string `json:"omitempty"`
}
SOLUTION2:
myextras := make(map[string]interface{})
// get Struct.Nested in map[string]interface{} format
myextras = Struct.Nest
myextras["Extra2"] = "zz"
// get Struct in map[string]interface{} format
struct["Nest"] = myextras
struct["Extra1"] = Nested{"yy"}
// solves the problem with lots of type casting but doesn't support json tag naming
有没有更好的解决方案来添加嵌套元素,这些元素不是用支持json-tag的struct数据类型表示的,可以用来输出到用户.