【问题标题】:SwiftyJSON won't parse a JSON string that will later parse with no issueSwiftyJSON 不会解析 JSON 字符串,该字符串稍后会毫无问题地解析
【发布时间】:2015-02-06 13:22:37
【问题描述】:

我有以下 PubNub 委托方法,它们按照下面声明的确切顺序被调用。

public func pubnubClient(client: PubNub!, didSubscribeOnChannels channels: NSArray!) {
    log.info("Subscribed to \(channels.count) channels")
    PubNub.sendMessage("{\"type\": \"CHAT_MSG\",\"msgId\": \"1233123\",\"text\": \"hello\",\"username\": \"attheodo\",\"uuid\": \"user_1\",\"associatedPlaceId\": 2}", toChannel:pubnubChannels[0])
}

public func pubnubClient(client: PubNub!, subscriptionDidFailWithError error: PNError!){
    log.error("Subscribe Error: \(error)")
}

// MARK: Messages
public func pubnubClient(client: PubNub!, willSendMessage message: PNMessage!) {

    let payload = JSON(message.message)
    println(payload)
    println(payload.rawString())
    println(_stdlib_getTypeName(payload))
    println(payload["type"])


}

public func pubnubClient(client: PubNub!, didReceiveMessage message: PNMessage!) {

    let payload = JSON(message.message)
    println(payload)
    println(payload.rawString())
    println(_stdlib_getTypeName(payload))
    println(payload["type"])

}

问题是 SwiftyJSON 无法正确解析 willSendMessage 返回的字符串,但会正确解析 didReceiveMessage 返回的字符串,尽管在我看来,它们似乎完全相同。这有点让我发疯。

请检查下面的相应控制台输出:

// willSendMessage
{"type": "CHAT_MSG","msgId": "1233123","text": "hello","username":     "attheodo","uuid": "user_1","associatedPlaceId": 2}

Optional("{\"type\": \"CHAT_MSG\",\"msgId\": \"1233123\",\"text\":  \"hello\",\"username\": \"attheodo\",\"uuid\": \"user_1\",\"associatedPlaceId\": 2}")

_TtV10SwiftyJSON4JSON

// cannot find payload["type"]
null

// didReceiveMessage
{
  "username" : "attheodo",
  "uuid" : "user_1",
  "msgId" : "1233123",
  "associatedPlaceId" : 2,
  "type" : "CHAT_MSG",
  "text" : "hello"
}

Optional("{\n  \"username\" : \"attheodo\",\n  \"uuid\" : \"user_1\",\n  \"msgId\" : \"1233123\",\n  \"associatedPlaceId\" : 2,\n  \"type\" : \"CHAT_MSG\",\n  \"text\" : \"hello\"\n}")

_TtV10SwiftyJSON4JSON

// payload["type"] is ok
CHAT_MSG

@#$!这是怎么回事?请帮忙,这会让我吃药>:|

【问题讨论】:

    标签: ios swift pubnub swifty-json


    【解决方案1】:

    PubNub 库会自动为您编码/解码 JSON 以用于对象类型,例如字典。尝试排除您对 3rd 方 JSON 库的使用并使用本机 Obj-c 字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多