dongtu1789
2017-09-18 12:15
浏览 117
已采纳

在JSON golang中编码/解码多类型字段

I am trying to create a struct where a field can hold data of a few particular types, say int, string and a CustomType. I want to decode/encode this struct to/from JSON. How can we achieve this in go/golang?

For example, I have a struct for the following definition:

type MyData struct {
  Name  string                                    `json:"name"`
  Value int32                                     `json:"value"`
  Param <can be either int, string or CustomType> `json:"param"`
}

Where CustomType is

type CustomType struct {
  Custom bool `json:"custom"`
}

Let's say I need to unmarshal the following JSONs to the above struct MyData:

{
  "name": "Hello",
  "value": 32
  "param": "World"
}

And this one:

{
  "name": "Hello",
  "value": 32
  "param": 100
}

And this one also:

{
  "name": "Hello",
  "value": 32
  "param": {
     "custom": true
  }
}

How do I achieve this?

Can I define my own MarshalJSON and UnmarshalJSON on MyData and achieve this?

Or is there a way of defining a custom type, say IntOrStringOrCustom and define MyData as

type MyData struct {
  Name  string              `json:"name"`
  Value int32               `json:"value"`
  Param IntOrStringOrCustom `json:"param"`
}

and then define MarshalJSON and UnmarshalJSON on IntOrStringOrCustom?

I have also seen json.RawMessage. Can we use it somehow here?

Issue with using interface{} is that I will have to write the encoding/decoding logic everywhere, where I am trying to use this data. Or is there an elegant way of doing this with interface{}?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题