Go 如何正确覆盖解组JSON?

Go 如何正确覆盖解组JSON?,go,Go,我正在尝试编写一个简单的自定义封送拆收器,但失败了。注意,我有一个接口,它有三个功能。Happy和Sadstruct都通过嵌入emotionstruct来实现此接口,该struct实现了所有三个必需的功能 问题是当我在指向Happy或Sad的指针上调用json.Unmarshal()时,UnmarshalJSON没有被调用,我不明白为什么。您可以在中复制确切的代码库,也可以查看下面的内容。您会注意到,虽然正确地调用了MarshalJSON,但没有正确地调用UnmarshalJSON type E

我正在尝试编写一个简单的自定义封送拆收器,但失败了。注意,我有一个接口,它有三个功能。
Happy
Sad
struct都通过嵌入
emotion
struct来实现此接口,该struct实现了所有三个必需的功能

问题是当我在指向
Happy
Sad
的指针上调用
json.Unmarshal()
时,
UnmarshalJSON
没有被调用,我不明白为什么。您可以在中复制确切的代码库,也可以查看下面的内容。您会注意到,虽然正确地调用了
MarshalJSON
,但没有正确地调用
UnmarshalJSON

type Emotion interface {
    String() string
    MarshalJSON() ([]byte, error)
    UnmarshalJSON(data []byte) error 
}

type emotion struct {
    status string
}

func (s emotion) String() string {
    return s.status
}

func (s emotion) MarshalJSON() ([]byte, error) {
        fmt.Println("MarshalJSON is overriden: I am called fine")
    x := struct {
        Status string
    }{
        Status: s.String(),
    }

    return json.Marshal(x)
}

func (s *emotion) UnmarshalJSON(data []byte) error {
        fmt.Println("MarshalJSON is overriden: I am never called")
    y := struct {
        Status string
    }{
        Status: "",
    }

    err := json.Unmarshal(data, &y)
    if err != nil {
        return err
    }

    s.status = y.Status
    return nil
}

type Happy struct {
    *emotion
}

// Job is not in any detention
type Sad struct {
    *emotion
}


func main() {
    x := Happy{&emotion{status: "happy"}}
    jsonX, _ := json.Marshal(x)
    var y Emotion
    err := json.Unmarshal(jsonX, &y)
    fmt.Printf("%v", err)
}

不能将其解组为抽象接口类型。 接口值只是一个指向某个类型(关联该类型和方法)的指针—它后面没有存储—因为抽象类型无法知道它将来可能拥有的任何具体值的确切大小

使用具体的值类型(也实现该接口)将起作用:

y2 := emotion{}
err = json.Unmarshal(jsonX, &y2)
游乐场:

MarshalJSON被覆盖:我被称为fine
预期错误,无法将对象解组为非具体值:json:无法将对象解组为main.Emotion类型的Go值
MarshalJSON被覆盖:我是(固定的),现在被调用
不应出现以下错误:
价值观:快乐

json.unmarshal。它无法知道您想要什么类型,因此返回一个错误。您的术语令人困惑。1) Go根本不允许重写。2) 解组JSON不用于封送JSON。顾名思义,它用于解组。
MarshalJSON is overriden: I am called fine
EXPECTED ERROR, Can't unmarshal into a non-concrete value: json: cannot unmarshal object into Go value of type main.Emotion

MarshalJSON is overriden: I am (fixed) and now called
SHOULD NOT ERROR: <nil>
VALUE: happy