SwiftyJSON不会解析稍后将解析而没有问题的JSON字符串

时间:2015-02-06 13:22:38

标签: ios swift pubnub swifty-json

我有以下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

@#$是什么!在这里?请帮忙,这会让我参加meds>:|

1 个答案:

答案 0 :(得分:0)

PubNub库将为您自动编码/解码JSON,用于对象类型,如词典。尝试排除使用第三方JSON库并使用本机Obj-c词典。