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?
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