我正在尝试解Marshal的JSON请求
Google Actions
. 它们具有如下标记的联合数组:
{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "foo"
}
}, {
"id": "456",
"customData": {
"fooValue": 12,
"barValue": false,
"bazValue": "bar"
}
}]
}
}]
}
{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [{
"devices": [{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "sheepdip"
}
}, {
"id": "456",
"customData": {
"fooValue": 36,
"barValue": false,
"bazValue": "moarsheep"
}
}],
"execution": [{
"command": "action.devices.commands.OnOff",
"params": {
"on": true
}
}]
}]
}
}]
}
etc.
很明显,我可以把这件事告诉
interface{}
并使用完全动态的类型转换和所有东西对其进行解码,但Go对结构的解码有很好的支持。有没有办法在围棋中优雅地做到这一点(
like you can in Rust
例如)?
我觉得你可以通过阅读demarshalling一开始的内容来做到这一点:
type Request struct {
RequestId string
Inputs []struct {
Intent string
Payload interface{}
}
}
然而,一旦您拥有
Payload interface{}
似乎没有任何方法将其反序列化为
struct
(除了序列化和反序列化之外,这很糟糕。有什么好的解决方案吗?