英文:
Handling dynamic JSON schema decoding
问题
我有一个Go HTTP客户端,用于发送/解析JSON-RPC
请求。
HTTP POST请求:
[
{"id":"1", "method":"action1","params":[]},
{"id":"2", "method":"action2","params":[]},
...
{"id":"X", "method":"actionX","params":[]}
]
HTTP响应:
[
{"id":"1", "error":null, "result":{...}},
{"id":"2", "error":null, "result":{...}},
...
{"id":"X", "error":null, "result":{...}}
]
如何处理那些result
键是一个具有动态模式的对象的有效负载,该模式取决于id
键的值。
英文:
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
.
答案1
得分: 2
你可以通过将结果解组为json.RawMessage
,来指示json库不解组结果字段。在这种情况下,将响应解组为一个切片:
type result struct{
ID string `json:"id"`
Err *string `json:"error"` // 可能是一个字符串?
Result json.RawMessage `json:"result"`
}
然后,当你知道要处理的ID时,你可以将result.ID
解组为另一个具有你期望的结构的结构体。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论