swift 将json字符串 转换成 字典

时间:2021-11-19 01:48:06

定义一个字符串或者是获取一个字符串

但是记得一定是json字符串哦

let dictionary_temp = "{\"to\":\"18037517130_8\",\"body\":{\"thumbnailLocalPath\":\"\",\"thumbnailSecretKey\":\"\",\"downloadStatus\":1,\"thumbnailSizeWidth\":0,\"sizeHight\":0,\"localPath\":\"\\/Users\\/tingyuxuan\\/Library\\/Developer\\/CoreSimulator\\/Devices\\/1A6A72D7-A5E4-40C4-9128-958201FA4CF6\\/data\\/Containers\\/Data\\/Application\\/A172FCF4-CEDA-4BF8-95E1-28D68022B65B\\/Documents\\/HyphenateSDK\\/chatbuffer\\/1467694526525.png\",\"remotePath\":\"\",\"secretKey\":\"\",\"sizeWidth\":0,\"thumbnailRemotePath\":\"\",\"thumbnailDownloadStatus\":3},\"messageId\":\"14676945265360040\",\"conversationId\":\"18037517130_8\",\"timestamp\":1467694526536,\"from\":\"18501360583_167\",\"isDeliverAcked\":false,\"isRead\":true,\"chatType\":0,\"serverTime\":1467694526536,\"isReadAcked\":false,\"ext\":{\"questionId_with_Ext\":\"102\",\"body_type\":2},\"status\":1,\"direction\":0}"

我这里是直接复制的获取的json字符串,格式可能不对,表达出意思就行了,大家见谅

if !dictionary_temp.isEmpty{
            let data = dictionary_temp.dataUsingEncoding(NSUTF8StringEncoding)! as NSData
            let dictionary_temp_temp = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
}
判断确定 dictionary_temp不是空的,然后进行转换

转换出来结果是  dictionary_temp_temp 是以字典的形式来呈现的

   {
        downloadStatus = 1;
        localPath = "/Users/tingyuxuan/Library/Developer/CoreSimulator/Devices/1A6A72D7-A5E4-40C4-9128-958201FA4CF6/data/Containers/Data/Application/A172FCF4-CEDA-4BF8-95E1-28D68022B65B/Documents/HyphenateSDK/chatbuffer/1467694526525.png";
        remotePath = "";
        secretKey = "";
        sizeHight = 0;
        sizeWidth = 0;
        thumbnailDownloadStatus = 3;
        thumbnailLocalPath = "";
        thumbnailRemotePath = "";
        thumbnailSecretKey = "";
        thumbnailSizeWidth = 0;
    };
    chatType = 0;
    conversationId = "18037517130_8";
    direction = 0;
    ext =     {
        "body_type" = 2;
        "questionId_with_Ext" = 102;
    };
    from = "18501360583_167";
    isDeliverAcked = 0;
    isRead = 1;
    isReadAcked = 0;
    messageId = 14676945265360040;
    serverTime = 1467694526536;
    status = 1;
    timestamp = 1467694526536;
    to = "18037517130_8";