drqvsx1228
drqvsx1228
2018-02-21 16:53
浏览 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
    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

    点赞 评论
  • duanqianpu6499
    duanqianpu6499 2018-02-21 16:59

    If you put marshalled JSON into a string, it will be marshalled as a string (because it's a string) and the receiving end will have to unmarshal it twice (because it's been marshalled twice). What you want is probably more along the lines of:

    type GeneralResponse struct {
        Success string
        Message string
        Data    interface{}  // interface{} can be anything
        Error   string
    }
    

    This way you can put any data into Data and it will be marshalled directly into the response.

    点赞 评论
  • dtlrp119999
    dtlrp119999 2018-02-21 17:00

    json.RawMessage comes to rescue in case you wants to capture whole json without knowing its format.

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

    Checkout this code. I have modified your code to dump data into response

    点赞 评论
  • dongwujie7477
    dongwujie7477 2018-02-21 17:07

    You can use json.RawMessage for that. I have implemented the encoding part, you find more here to decode - https://golang.org/pkg/encoding/json/#RawMessage

    点赞 评论

相关推荐