I want to parse some JSON but one key is either a string or an object.
Here is my current struct: https://github.com/PhillippOhlandt/pmtoapib/blob/master/CollectionItemRequest.go#L10
type CollectionItemRequest struct { Url string `json:"url"` Method string `json:"method"` Header []RequestHeader `json:"header"` Body RequestBody `json:"body"` Description string `json:"description"` } Here the "Url" attribute can not only a string but also an object.
I started to create an own struct for it that covers the object case.
type CollectionItemRequestUrl struct { Raw string `json:"raw"` } type CollectionItemRequest struct { Url CollectionItemRequestUrl `json:"url"` Method string `json:"method"` Header []RequestHeader `json:"header"` Body RequestBody `json:"body"` Description string `json:"description"` } But then the string version won't work anymore. Is there a way to have both cases working and getting the value via a getter, like request.Url.Get?
EDIT:
Here are the two versions of the JSON:
"request": { "url": { "raw": "http://localhost:8081/users?per_page=5&page=2", "protocol": "http", "host": [ "localhost" ], "port": "8081", "path": [ "users" ], "query": [ { "key": "per_page", "value": "5", "equals": true, "description": "" }, { "key": "page", "value": "2", "equals": true, "description": "" } ], "variable": [] }, And
"request": { "url": "http://localhost:8081/users/2", Note: Only subsets, the whole JSON would be too long.
UnmarshalJSONfunction should work just fine in this case.