我一直在尝试解析来自 PubNub 的 JSON 消息,但没有成功:
type PubNubMessage struct {
body []string
}
[[{"text":"hey"}],"1231212412423235","channelName"]
json: cannot unmarshal array into Go value of type main.PubNubMessage
有人知道如何在 golang 中解码如此复杂的类型吗?
最佳答案
简短的回答是,您不能直接将非同质类型的 JSON 数组(根据您的示例)解码到 golang 结构中。
长答案是您应该定义 (m *PubNubMessage) UnmarshalJSON([]byte) error
method对于您的 PubNubMessage 类型,它将 JSON 字符串解码到接口(interface){}
,然后使用类型断言来确保预期的格式并填充结构。
例如:
type TextMessage struct {
Text string
}
type PubNubMessage struct {
Messages []TextMessage
Id string
Channel string
}
func (pnm *PubNubMessage) UnmarshalJSON(bs []byte) error {
var arr []interface{}
err := json.Unmarshal(bs, &arr)
if err != nil {
return err
}
messages := arr[0].([]interface{}) // TODO: proper type check.
pnm.Messages = make([]TextMessage, len(messages))
for i, m := range messages {
pnm.Messages[i].Text = m.(map[string]interface{})["text"].(string) // TODO: proper type check.
}
pnm.Id = arr[1].(string) // TODO: proper type check.
pnm.Channel = arr[2].(string) // TODO: proper type check.
return nil
}
// ...
jsonStr := `[[{"text":"hey"},{"text":"ok"}],"1231212412423235","channelName"]`
message := PubNubMessage{}
err := json.Unmarshal([]byte(jsonStr), &message)
关于json - 使用 golang JSON 解码 PubNub 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29348262/