简体   繁体   English

MarshalJSON字符串声明的类型

[英]MarshalJSON a String Declared Type

I have created a new declared type and added a method to marshal the value into JSON 我创建了一个新的声明类型,并添加了一种将值编组为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"}

You have to define the MarshalJSON interface as a non-pointer. 您必须将MarshalJSON接口定义为非指针。

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

Play Link: https://play.golang.org/p/lLK6zsAkOi 播放链接: https : //play.golang.org/p/lLK6zsAkOi

Output: 输出:

{"data":"Test test"}

The root of the problem stems from how interfaces in Go are implicitly satisfied. 问题的根源在于如何隐式满足Go中的接口。
In this particular case, the json.Marshal method uses type assertion at runtime to see if the given value implements json.Marshaler . 在此特定情况下, json.Marshal方法在运行时使用类型断言来查看给定值是否实现json.Marshaler Effective Go mentions this very case . 有效的Go 提到了这种情况

You could have satisfied the json.Marshaler for the *TextOutput type using a pointer-receiver like so: 您可以使用指针接收器满足*TextOutput类型的json.Marshaler要求,如下所示:

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: 为了使其正常工作,请将引用传递给json.Marshal函数:

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 但是,使用值接收器实现它可以确保TextOutput*TextOutput类型都实现json.Marshaler

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM