JSON 编组产生意外结果
JSON Marshaling producing unexpected results
这是一个演示我的问题的 Go Playground:http://play.golang.org/p/2fq3Fg7rPg
本质上,我正在尝试 JSON 编组包含自定义类型包装的结构 json.RawMessage
。使用 CustomType.MarshalJSON()
时,我得到了预期的结果,但仅在我的完整结构上调用 json.Marshal
并没有按预期工作。有关具体示例,请参阅操场 link。
造成这种差异的原因是什么?
有没有办法让 json.Marshal
像我期望的那样工作?
您的代码工作正常,只有一个小错误。
// MarshalJSON returns the *j as the JSON encoding of j.
func (j JsonText) MarshalJSON() ([]byte, error) {
return j, nil
} // note i modified this so the receiver isn't a pointer
您的代码无效,因为这是您对包装 JsonText 的数据类型的定义;
// Example struct I want to marshal and unmarshal
type TestData struct {
Field1 JsonText `json:"field_1"`
}
但是只有 *JsonText
类型在您的代码中实现了编组器接口。所以你可以在任何一个地方更改类型(我在 MarshalJSON()
中做了)但它们需要保持一致。
这是一个演示我的问题的 Go Playground:http://play.golang.org/p/2fq3Fg7rPg
本质上,我正在尝试 JSON 编组包含自定义类型包装的结构 json.RawMessage
。使用 CustomType.MarshalJSON()
时,我得到了预期的结果,但仅在我的完整结构上调用 json.Marshal
并没有按预期工作。有关具体示例,请参阅操场 link。
造成这种差异的原因是什么?
有没有办法让 json.Marshal
像我期望的那样工作?
您的代码工作正常,只有一个小错误。
// MarshalJSON returns the *j as the JSON encoding of j.
func (j JsonText) MarshalJSON() ([]byte, error) {
return j, nil
} // note i modified this so the receiver isn't a pointer
您的代码无效,因为这是您对包装 JsonText 的数据类型的定义;
// Example struct I want to marshal and unmarshal
type TestData struct {
Field1 JsonText `json:"field_1"`
}
但是只有 *JsonText
类型在您的代码中实现了编组器接口。所以你可以在任何一个地方更改类型(我在 MarshalJSON()
中做了)但它们需要保持一致。