使用golang JSON解码PubNub消息 [英] Decoding PubNub messages with golang JSON

查看:123
本文介绍了使用golang JSON解码PubNub消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从PubNub解析此JSON消息,但没有任何运气:

I've been trying to parse this JSON message from PubNub without any luck:

type PubNubMessage struct {
    body []string
}

[[{"text":"hey"}],"1231212412423235","channelName"]
json: cannot unmarshal array into Go value of type main.PubNubMessage

有人知道如何在golang中解码这种复杂类型吗?

Does anyone have an idea on how to decode such complex types in golang?

推荐答案

简短的答案是,您不能直接将非同类型的JSON数组(按您的示例)解组到golang结构中.

The short answer is that you cannot directly unmarshal a JSON array of non-homogenous types (per your example) into a golang struct.

长答案是,您应该定义一个 (m *PubNubMessage) UnmarshalJSON([]byte) error方法为您的PubNubMessage类型,该类型将JSON字符串解组为interface{},然后使用类型断言来确保期望的格式并填充结构.

The long answer is that you should define an (m *PubNubMessage) UnmarshalJSON([]byte) error method for your PubNubMessage type which unmarshals the JSON string into an interface{} and then uses type assertions to ensure the expected format and populates the structure.

例如:

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)

这篇关于使用golang JSON解码PubNub消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆