dtyz76562 2013-04-14 08:07
浏览 81
已采纳

解组异构结构的JSON数组

I want to deserialise an object that includes an array of a some interface Entity:

type Result struct {
    Foo int;
    Bar []Entity;
};

Entity is an interface that is implemented by a number of struct types. JSON data identifies the struct type with a "type" field in each entity. E.g.

{"type":"t1","field1":1}
{"type":"t2","field2":2,"field3":3}

How would I go about deserialising the Result type in such a way that it correctly populates the array. From what I can see, I have to:

  1. Implement UnmarshalJSON on Result.
  2. Parse Bar as a []*json.RawMessage.
  3. Parse each raw message as map[string]interface{}.
  4. Check "type" field in the raw message.
  5. Create a struct of appropriate type.
  6. Parse the raw message again, this time into the just created struct.

This all sounds very tedious and boring. Is there a better way to do this? Or am I doing it backwards, and there is a more canonical method to handle an array of heterogeneous objects?

  • 写回答

1条回答 默认 最新

  • duanjiao5261 2013-04-14 12:37
    关注

    I think your process is probably a bit more complicated than it has to be, see http://play.golang.org/p/0gahcMpuQc. A single map[string]interface{} will handle a lot of that for you.

    Alternatively, you could make a type like

    struct EntityUnion {
        Type string
        // Fields from t1
        // Fields from t2
        // ...
    }
    

    Unmarshal into that; it will set the Type string and fill in all the fields it can get from the JSON data. Then you just need a small function to copy the fields to the specific type.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?