dongxin991209 2016-08-30 15:36
浏览 44
已采纳

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

I have a problem deserializing my object. I use an interface to this object to call the Serialization, and from reading the output the serialization works perfectly. Here is the underlying struct of my object:

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

And here's the interface it implements:

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

The Serialize() method:

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

As you may have noticed, pimp has a variable by the name of Item. This item is also, an interface:

type item struct {
    Name string
}

type Item interface {
    GetName() string
}

Now serializing a sample of such an object returns the following JSON:

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

Here is my deserialization code:

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

Running it, however, gives me the following error:

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

Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • douxuexiao1748 2016-08-30 15:46
    关注

    The unmarshaler does not know the concrete type to use for the nil BidItem field. You can fix this by setting the field to a value of the appropriate type:

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

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度