json - 使用 golang JSON 解码 PubNub 消息

标签 json go pubnub

我一直在尝试解析来自 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/

相关文章:

c# - 如何在不创建新类的情况下将简单的 JSON 对象发送到 ASP.NET?

java - 找不到 LibGDX 文件

javascript - 如何在使用 $.post 向 PHP 发送和接收数据以及完成和失败函数时读取 JSON 响应

go - 使用neo4j驱动程序时使用match语句,返回的result.record为nil

ios - PubNub 发布订阅如何在 iOS 内部工作(客户端)

php - 将 SQLite 数据库放入 JSON 对象中以从 iOS 发送到服务器

xml - 将 Go 结构体转换为字符串

templates - Golang 模板 : for construction

node.js - 处理 PubNub channel 组限制

javascript - 使用 PubNub for Javascript 检测断开连接