JSON封送处理产生意外结果
Here is a Go Playground demonstrating my problem: http://play.golang.org/p/2fq3Fg7rPg
Essentially, I am trying to JSON marshal a struct containing a custom type wrapping json.RawMessage
. When using CustomType.MarshalJSON()
I get the expected results, but just calling json.Marshal
on my full struct does not work as expected. See the playground link for a concrete example.
What is causing this difference?
Is there a way to have json.Marshal
work as I expect it to?
这里是一个围棋场,展示了我的问题: http://play.golang.org/p/2fq3Fg7rPg p>
本质上,我正在尝试对包含以下内容的JSON封送结构 自定义类型包装 造成这种差异的原因是什么? p>
是否可以使用 json.RawMessage code>。 当使用
CustomType.MarshalJSON() code>时,我得到了预期的结果,但是仅在我的完整结构上调用
json.Marshal code>不能按预期的方式工作。 p>
json.Marshal 可以正常工作? p>
div>
Your code works fine, you just have one little bug.
// 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
Your code didn't work because this is your definition of your datatype that wraps JsonText;
// Example struct I want to marshal and unmarshal
type TestData struct {
Field1 JsonText `json:"field_1"`
}
But only the *JsonText
type implements the marshaler interface in your code. So you can change the types in either place ( I did in the MarshalJSON()
) but they need to be consistent.
In the playground; http://play.golang.org/p/NI_z3bQx7a