jordan2175
jordan2175

Reputation: 938

How to decode JSON based on object type in Golang

If you have the following JSON structure:

[
  {
    "type": "home",
    "name": "house #1",
    ... some number of properties for home #1
  },
  {
    "type": "bike",
    "name": "trek bike #1",
    ... some number of properties for bike #1
  },
  {
    "type": "home",
    "name": "house #2",
    ... some number of properties for home #2
  }
]

How do you decode this in Golang to a struct without knowing what each type is until you unmarshall the object. It seems like you would have to do this unmarshalling twice.

Also from what I can tell, I should probably be using the RawMessage to delay the decoding. But I am not sure how this would look.

Say I had the following structs:

type HomeType struct {
  Name                  string       `json:"name,omitempty"`
  Description           string       `json:"description,omitempty"`
  Bathrooms             string       `json:"bathrooms,omitempty"`
  ... more properties that are unique to a home
}

type BikeType struct {
  Name                  string       `json:"name,omitempty"`
  Description           string       `json:"description,omitempty"`
  Tires                 string       `json:"tires,omitempty"`
  ... more properties that are unique to a bike
}

Second question. Is it possible to do this in streaming mode? For when this array is really large?

Thanks

Upvotes: 1

Views: 1555

Answers (1)

Blue Bot
Blue Bot

Reputation: 2438

If you want to manipulate the objects you will have to know what type they are. But if you only want to pass them over, for example: If you get from DB some big object only to Marshal it and pass it to client side, you can use an empty interface{} type:

type HomeType struct {
  Name                  interface{}        `json:"name,omitempty"`
  Description           interface{}        `json:"description,omitempty"`
  Bathrooms             interface{}        `json:"bathrooms,omitempty"`
  ... more properties that are unique to a home
}

type BikeType struct {
  Name                  interface{}        `json:"name,omitempty"`
  Description           interface{}        `json:"description,omitempty"`
  Tires                 interface{}        `json:"tires,omitempty"`
  ... more properties that are unique to a bike
}

Read here for more about empty interfaces - link

Hope this is what you ment

Upvotes: 2

Related Questions