drqvsx1228 2018-02-21 16:53 采纳率: 0%
浏览 45
已采纳

GoLang中的动态嵌套结构

I am learning golang and want to write generic response from microservices response.

My General Response is like:

type GeneralResponse struct {
    Success string
    Message string
    Data    string
    Error   string
}

In the Data section I want to return any json, say list of Person, Instruments or any type of objects.

But it should be another json. I tried assigning other json objects but it did not work. It is fine if I dump json array as string into it but it should unmarshal from receiver end. How should I go about it?

I am trying over here. https://play.golang.org/p/dc0uKtS76aA

  • 写回答

4条回答 默认 最新

  • dongzuan4491 2018-02-21 16:57
    关注

    You should use RawMessage in the type definition

    type GeneralResponse struct {
      Success string
      Message string
      Data    json.RawMessage
      Error   string
    }
    

    and subsequently push a Marshalled json into that attribute. You can do that by encoding other types in []bytes and setting them to the Data attribute.

    Like in https://play.golang.org/p/CyoN5pe_aNV

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?