This question already has an answer here:
Trying to find a simple solution to marshaling/unmashaling into the following struct
type Resource struct {
Data []ResourceData `json:"data"`
}
type ResourceData struct {
Id string `json:"id"`
Type string `json:"type"`
Attributes map[string]interface{} `json:"attributes"`
Relationships map[string]Resource `json:"relationships"`
}
r := Resource{}
json.Unmarshal(body, &r)
this is great if:
body = `{"data":[{"id":"1","type":"blah"}]}`
However I also need it to respond to:
body = `{"data":{"id":"1","type":"blah"}}` //notice no slice
I could make a separate type
type ResourceSingle struct {
Data ResourceData `json:"data"`
}
However, that would mean needing to duplicate all the functions I have attached to resource, which is possible. However, i would need to find out which type to unmarshal into before executing it, plus when it comes to the relationships part, each of those could contain data:[]{} or data{}, so that idea isn't going to work.
Alternatively I could use
map[string]*json.RawMessage
//or
type Resource struct {
Data *json.RawMessage `json:"data"`
}
but still, when in json form how do I know if it is a slice or a node to supply the correct struct to unmarshal into?
My last resort is to umarshal into map[string]interface and use lots of reflect testing .. but this is very long winded.
Ideas?
Kind regards, jJ
</div>