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

时间:2016-08-30 15:36:50

标签: json serialization go

我有一个问题反序列化我的对象。我使用这个对象的接口来调用序列化,并且通过读取输出,序列化可以完美地工作。这是我的对象的基础结构:

type pimp struct {
    Price       int
    ExpDate     int64
    BidItem     Item
    CurrentBid  int
    PrevBidders []string
}

这是它实现的界面:

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

Serialize()方法:

func (p *pimp) Serialize() ([]byte, error) {
    return json.Marshal(*p)
}

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

type item struct {
    Name string
}

type Item interface {
    GetName() string
}

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

{"Price":100,"ExpDate":1472571329,"BidItem":{"Name":"ExampleItem"},"CurrentBid":100,"PrevBidders":[]}

这是我的反序列化代码:

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

然而,运行它会给我以下错误:

json: cannot unmarshal object into Go value of type Auction.Item

感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

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

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

playground example

相关问题