1

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

jordan2175
  • 878
  • 2
  • 10
  • 20
  • If there's a "type" field, and all the attributes are strings, why not just unmarshal into `[]map[string]string`? – JimB Nov 22 '16 at 18:28
  • Imagine the JSON objects having lots of properties including sub-objects and arrays of objects. – jordan2175 Nov 22 '16 at 18:35

1 Answers1

2

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

Community
  • 1
  • 1
Blue Bot
  • 2,278
  • 5
  • 23
  • 33