登录
首页 >  Golang >  Go问答

正确实现 JSON 反序列化的方法

来源:stackoverflow

时间:2024-02-24 22:18:24 186浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《正确实现 JSON 反序列化的方法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在尝试编写一个简单的自定义封送拆收器,但失败了。请注意,我有一个具有三个功能的界面。 happysad 结构体都通过嵌入实现所有三个必需功能的 emotion 结构体来实现此接口。

问题是当我在指向 happysad 的指针上调用 json.unmarshal() 时,unmarshaljson 不会被调用,我无法理解为什么。您可以在 go 演示中重现确切的代码库,或者直接看下面。您会注意到,虽然 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)

演示:https://play.golang.org/p/8aCEjLgfKVQ

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: 
VALUE: happy

到这里,我们也就讲完了《正确实现 JSON 反序列化的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>