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.

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

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)