我很好奇为什么我的 json 格式不正确。我试图添加一个数组字典,我弄明白了,我的 json 格式不正确,ACTIVE_CHATS 和 INACTIVE_CHATS 应该是我在 swift3 上由 .append(value) 创建的数组列表。但是在我对我的 react stringify 尝试 JSON.parse 之后,我得到了未捕获的 json 位置。我咨询了 android 团队,发现数组应该是 [] 而不是 () .. 我如何在 swift 中获得正确的 json 格式?
我现在的json格式是错误的
{
"ACTIVE_CHATS" = (
);
"INACTIVE_CHATS" = (
{
"app_token" = "someapptoken";
"channel_name" = "Channel-1";
icon = "https://media.icon.com/icons/appicon-1.jpg";
"last_message" = "some message";
"time_since_last_message" = "2017-03-28 06:13:33 +0000";
"unread_messages" = 3;
}
);
"ALL_CHAT" = {
"app_token" = "someapptoken";
"channel_name" = "Channel-2";
icon = "https://media.icon.com/icons/appicon-2.jpg";
"last_message" = "Some message";
"time_since_last_message" = "2017-03-28 06:13:33 +0000";
"unread_messages" = 3;
};
}
我在 swift 中创建 json 时的代码
var activearray = Array<Any>()
var inactivearray = Array<Any>()
var testdict = [String: Any]()
var counter = 0
for data in array {
var listMessage : [Any?] = (Smooch.conversation()?.messages)!
let unreadMsgCount = Smooch.conversation()?.unreadCount
if listMessage.count == 0{
continue
}
var iconUrl = ""
var channelName = ""
for msg in listMessage {
let msgSkt = msg as! SKTMessage
if (!msgSkt.isFromCurrentUser) {
iconUrl = (msg as! SKTMessage).avatarUrl!
channelName = (msg as! SKTMessage).name!
break
}
}
let lastMsg : SKTMessage = listMessage[listMessage.count - 1] as! SKTMessage
let lastMsgText : String = lastMsg.text!
let epTime : Date = lastMsg.date!
var dict = [String: Any]()
dict = ["unread_messages":unreadMsgCount! as UInt,"icon":iconUrl,"channel_name":channelName,"last_message":lastMsgText,"time_since_last_message":epTime,"app_token":array[counter]]
if counter == 0 {//put all
testdict["ALL_CHAT"] = dict
}else if counter > 0 && unreadMsgCount! > 0{// add active
activearray.append(dict)
}else{//add unactive
inactivearray.append(dict)
}
counter += 1
}
testdict["ACTIVE_CHATS"] = activearray
testdict["INACTIVE_CHATS"] = inactivearray
最佳答案
根据我们在评论中的讨论,您面临的问题是因为您输出了 NSDictionary
作为其字符串表示(或描述,如果您愿意)而不是实际输出有效的 JSON :)
你需要做的是将最终要转换为JSON格式的NSDictionary传递给JSONSerialization
的data(withJSONObject:options:)
方法。
在 Swift 中,代码看起来像这样:
do {
let data = try JSONSerialization.data(withJSONObject:testdict, options: JSONSerialization.WritingOptions.prettyPrinted)
let str = String(data:data, encoding: String.Encoding.utf8)
print(str)
} catch {
print("JSON error")
}
关于javascript - 来自 Swift 转换的 json 字符串导致 JSON 解析失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43063187/