处理动态JSON模式解码

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

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.

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:

确定