dongweihuan8610 2015-07-15 17:59
浏览 7
已采纳

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?

  • 写回答

1条回答 默认 最新

  • duanba7653 2015-07-15 18:14
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址