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

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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.