簡體   English   中英

NSJSONSerialization弄亂了生成的NSDictionary

[英]NSJSONSerialization messing up resulting NSDictionary

我在解析Web服務的json輸出時遇到問題。 我正在使用NSJSONSerialization將輸出解析為NSDictionary。 通過將AFHTTPSessionManager子類化也可以使用AFNetworking。 現在,響應序列化器是AFHTTPResponseSerializer,它返回NSData。這是我正在使用的代碼:

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&err];

非常簡單。 err對象為nil,因此轉換正常。

但是:我直接從Web服務獲得的結果是:

           "address":
           {
               "address1": "Ivy House",
               "address2": "Sandy Lane",
               "city": "Rush",
               "postCode": null,
               "email": "notknown@whatever.com",
               "telephone": "18437584",
               "mobile": null,
               "smsAlert": null,
               "county": "Dublin",
               "country": "Ireland",
               "websiteAddress": "www.example.com"
           },

打印dict的內容后得到的結果是:

address =     {
    address1 = "Ivy House";
    address2 = "Sandy Lane";
    city = Rush;
    country = Ireland;
    county = Dublin;
    email = "notknown@whatever.com";
    mobile = "<null>";
    postCode = "<null>";
    smsAlert = "<null>";
    telephone = 18437584;
    websiteAddress = "www.example.com";
};

問題在於生成的NSDictionary沒有雙引號,因此將NSDictionary以plist格式保存到磁盤失敗!

我也嘗試過使用AFJSONResponseSerializer返回NSDictionary,但內容與上面相同!

這里的問題在哪里?

提前致謝。

這里的問題似乎根本與雙引號無關。 在打印時, NSDictionary (以及其他Foundation對象)在不需要雙引號時(例如,字符串中沒有空格或特殊字符時)會刪除雙引號。

現在,阻止您將NSDictionary序列化到屬性列表的可能問題是JSON中(因此,在NSDictionary中)存在nulls 根據文件

屬性列表對象包括NSDataNSStringNSArrayNSDictionaryNSDateNSNumber對象。

而JSON中的nulls將被表示為NSNull實例,從而使您的NSDictionary成為無效的屬性列表。

NSDictionary具有與JSON字符串不同的結構。 因此,當您將JSON字符串解析為NSDictionary時,您不應期望引號。

您可以保存JSON數據,然后在運行時再次對其進行解析。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"yourfilename.dat"];

 // Save it into file system
[data writeToFile:dataPath atomically:YES];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM