使用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)在Go操场上运行此示例将返回
{A:1B:default b C:3}。如您所见,
json.Unmarshal(example, &out)将JSON解组为
out,覆盖JSON中指定的值,但其他字段保持不变。



