duanbi9202 2017-08-03 18:50
浏览 38
已采纳

MarshalJSON字符串声明的类型

I have created a new declared type and added a method to marshal the value into JSON

type TextOutput string

func (t *TextOutput) MarshalJSON() ([]byte, error) {
    return []byte(fmt.Sprintf(`{"data": "%s"}`, t)), nil
}

When I try to marshal an instance of the type I get the raw value returned. What am I missing?

var t TextOutput
t = `Test test`
output, err := json.Marshal(t)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(string(output))
}
// prints Test Test. Expected {"data": "Test test"}
  • 写回答

2条回答 默认 最新

  • douye2572 2017-08-03 20:49
    关注

    The root of the problem stems from how interfaces in Go are implicitly satisfied.
    In this particular case, the json.Marshal method uses type assertion at runtime to see if the given value implements json.Marshaler. Effective Go mentions this very case.

    You could have satisfied the json.Marshaler for the *TextOutput type using a pointer-receiver like so:

    func (t *TextOutput) MarshalJSON() ([]byte, error) {
        return []byte(fmt.Sprintf(`{"data":"%s"}`, *t)), nil
    }
    

    And for this to work properly, pass the reference to the json.Marshal function:

    var t TextOutput
    t = `Test test`
    output, err := json.Marshal(&t) 
    

    However, implementing it using a value-receiver ensures that both TextOutput and *TextOutput types implement json.Marshaler

    func (t TextOutput) MarshalJSON() ([]byte, error) {
        return []byte(fmt.Sprintf(`{"data": "%s"}`, t)), nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)