这是一个演示我的问题的游乐场:http://play.golang.org/p/2fq3Fg7rPg

本质上,我正在尝试将包含自定义类型的结构JSONt_code JSON结构封送。使用json.RawMessage时,可以得到预期的结果,但是仅在我的完整结构上调用CustomType.MarshalJSON()不能按预期的方式工作。有关具体示例,请参见操场链接。

是什么造成了这种差异?

有没有一种方法可以像我期望的那样运行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类型在您的代码中实现了marshaler接口。因此,您可以在任一位置更改类型(我在MarshalJSON()中进行了更改),但是它们需要保持一致。

在操场; http://play.golang.org/p/NI_z3bQx7a

关于json - JSON编码(marshal)处理产生意外结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31437749/

10-13 03:22