json:无法将对象解组为 Auction.Item 类型的 Go 值

wal*_*ken 2 serialization json go

我在反序列化我的对象时遇到问题。我使用这个对象的接口来调用序列化,从读取输出序列化工作完美。这是我的对象的底层结构:

type pimp struct {
    Price       int
    ExpDate     int64
    BidItem     Item
    CurrentBid  int
    PrevBidders []string
}
Run Code Online (Sandbox Code Playgroud)

这是它实现的接口:

type Pimp interface {
    GetStartingPrice() int
    GetTimeLeft() int64
    GetItem() Item
    GetCurrentBid() int
    SetCurrentBid(int)
    GetPrevBidders() []string
    AddBidder(string) error
    Serialize() ([]byte, error)
}
Run Code Online (Sandbox Code Playgroud)

Serialize() 方法:

func (p *pimp) Serialize() ([]byte, error) {
    return json.Marshal(*p)
}
Run Code Online (Sandbox Code Playgroud)

您可能已经注意到,pimp 有一个名为 Item 的变量。这一项也是,一个接口:

type item struct {
    Name string
}

type Item interface {
    GetName() string
}
Run Code Online (Sandbox Code Playgroud)

现在序列化此类对象的样本将返回以下 JSON:

{"Price":100,"ExpDate":1472571329,"BidItem":{"Name":"ExampleItem"},"CurrentBid":100,"PrevBidders":[]}
Run Code Online (Sandbox Code Playgroud)

这是我的反序列化代码:

func PimpFromJSON(content []byte) (Pimp, error) {
    p := new(pimp)
    err := json.Unmarshal(content, p)
    return p, err
}
Run Code Online (Sandbox Code Playgroud)

但是,运行它会给我以下错误:

json: cannot unmarshal object into Go value of type Auction.Item
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

Cer*_*món 5

解组器不知道用于 nilBidItem字段的具体类型。您可以通过将字段设置为适当类型的值来解决此问题:

func PimpFromJSON(content []byte) (Pimp, error) {
    p := new(pimp)
    p.BidItem = &item{}
    err := json.Unmarshal(content, p)
    return p, err
}
Run Code Online (Sandbox Code Playgroud)

游乐场示例