Home > Net >  Handling dynamic JSON schema decoding
Handling dynamic JSON schema decoding

Time:09-28

I have a Go HTTP client which sends/parses JSON-RPC requests.

HTTP POST Request :

[
   {"id":"1", "method":"action1","params":[]},
   {"id":"2", "method":"action2","params":[]},
   ...
   {"id":"X", "method":"actionX","params":[]}
]

HTTP response :

[
   {"id":"1", "error":null, "result":{...}},
   {"id":"2", "error":null, "result":{...}},
   ...
   {"id":"X", "error":null, "result":{...}}
]

How to handle those payloads where the result key is an object with dynamic schema depending on the value of the key id.

CodePudding user response:

You can instruct the json library not to unmarshal the result field by unmarshaling the result into a json.RawMessage, in this case unmarshal the response into a slice of:

type result struct{
    ID     string          `json:"id"`
    Err    *string         `json:"error"` // maybe a string?
    Result json.RawMessage `json:"result"`
}

Then when you know which ID you are dealing with you can unmarshal result.ID into another struct with the structure you expect.

  • Related