type Struct struct {
Value string `json:"value"`
Value1 string `json:"value_one"`
Nest Nested `json:"nest"`
}
type Nested struct {
Something string `json:"something"`
}
我希望能在不创建另一个结构体类型的情况下添加未在结构体定义中的元素。例如:
Struct.Extra1 = Nested{"yy"}
Struct.Nested.Extra2 = "zz"
这将导致
{
"Value": "xx",
"Value1": "xx",
"Extra1": {
"Something", "yy"
},
"Nest": {
"Something": "xx",
"Extra2": "zz"
}
}
解决方案1:
我考虑添加omitempty
来实现这一目标,但这会使结构体变得复杂。
type Struct struct {
Value string
Value1 string
Nest Nested
Extra1 Nested `json:"omitempty"`
}
type Nested struct {
Something string
Extra2 string `json:"omitempty"`
}
解决方案2:
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
有没有更好的解决方案来添加嵌套元素,这些元素在struct数据类型中没有表示,并且支持json标记,可以用于输出给用户?