处理动态JSON模式解码

huangapple go评论119阅读模式
英文:

Handling dynamic JSON schema decoding

问题

我有一个Go HTTP客户端,用于发送/解析JSON-RPC请求。

HTTP POST请求:

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

HTTP响应:

  1. [
  2. {"id":"1", "error":null, "result":{...}},
  3. {"id":"2", "error":null, "result":{...}},
  4. ...
  5. {"id":"X", "error":null, "result":{...}}
  6. ]

如何处理那些result键是一个具有动态模式的对象的有效负载,该模式取决于id键的值。

英文:

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

HTTP POST Request :

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

HTTP response :

  1. [
  2. {"id":"1", "error":null, "result":{...}},
  3. {"id":"2", "error":null, "result":{...}},
  4. ...
  5. {"id":"X", "error":null, "result":{...}}
  6. ]

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库不解组结果字段。在这种情况下,将响应解组为一个切片:

  1. type result struct{
  2. ID string `json:"id"`
  3. Err *string `json:"error"` // 可能是一个字符串?
  4. Result json.RawMessage `json:"result"`
  5. }

然后,当你知道要处理的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:

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

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

huangapple
  • 本文由 发表于 2021年9月28日 00:05:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/69349827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定