我想在Go中解析JSON对象,但是想为未给出的字段指定默认值.例如,我有结构类型:
type Test struct {
A string
B string
C string
}
Run Code Online (Sandbox Code Playgroud)
A,B和C的默认值分别是"a","b"和"c".这意味着当我解析json时:
{"A": "1", "C": 3}
Run Code Online (Sandbox Code Playgroud)
我想得到结构:
Test{A: "1", B: "b", C: "3"}
Run Code Online (Sandbox Code Playgroud)
这可能使用内置包encoding/json
吗?否则,是否有任何Go库具有此功能?
JW.*_*JW. 57
这可以使用encoding/json:在调用时json.Unmarshal
,你不需要给它一个空结构,你可以给它一个默认值.
对于你的例子:
var example []byte = []byte(`{"A": "1", "C": "3"}`)
out := Test{
A: "default a",
B: "default b",
// default for C will be "", the empty value for a string
}
err := json.Unmarshal(example, &out) // <--
if err != nil {
panic(err)
}
fmt.Printf("%+v", out)
Run Code Online (Sandbox Code Playgroud)
在Go playground中运行此示例返回{A:1 B:default b C:3}
.
如您所见,json.Unmarshal(example, &out)
将JSON解组为out
,覆盖JSON中指定的值,但保持其他字段不变.
Chr*_*ian 11
如果您有Test
结构列表或地图,则不再可以接受答案,但可以使用UnmarshalJSON方法轻松扩展:
func (t *Test) UnmarshalJSON(data []byte) error {
type testAlias Test
test := &testAlias{
B: "default B",
}
_ = json.Unmarshal(data, test)
*t = Test(*test)
return nil
}
Run Code Online (Sandbox Code Playgroud)
需要testAlias来防止对UnmarshalJSON的递归调用.这是有效的,因为新类型没有定义方法.
https://play.golang.org/p/qiGyjRbNHg