在快速不一致的情况下解析JSON

时间:2016-01-26 18:43:52

标签: ios json swift parsing

我遇到了我认为是一个错误。我有一个从服务器返回的对象数组。但是,当从中提取值时,我会得到不一致的结果。这些项中的每一项都与服务器的响应数组相同:

当我尝试提取此quantity的值时,它会返回Int

{
    address = "4040 MARKET ST RM 226";
    city = PHILADELPHIA;
    ln = "AMOXICILLIN 500 MG CAPSULE";
    ndc = 57237003105;
    npi = 1619912375;
    "pharmacy_name" = "GRACE PHARMACY INC";
    phone = "(215)895-5594";
    price = "8.00";
    quantity = 500;
    state = PA;
    vendor = una;
    zip = 19104;
}

但是,当我尝试从此quantity中提取String时,它会以{ address = "1826 Chestnut St # 30"; brand = G; city = Philadelphia; distance = "0.06"; latitude = "39.951747"; ln = "AMOXICILLIN 500 MG CAPSULE"; longitude = "-75.171154"; "ncpdp_id" = 3969485; ndc = 65862001705; "pharmacy_hours_of_operation" = "Open 24 Hours"; "pharmacy_name" = "CVS PHARMACY"; phone = "(215)972-0909"; price = "11.82"; quantity = 30; state = PA; vendor = scriptsave; zip = "19103-4902"; } 的形式返回。

let searchResultsJSON: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as! NSDictionary

为什么世界会发生这种情况?除了一个中的一些额外值之外,两个对象似乎都是相同的。

===

像这样序列化JSON:

    quantity            = formDictionary["quantity"] as? Int
    quantityString      = formDictionary["quantity"] as? String

抓住这样的价值观:

results =     (
                {
            address = "4040 MARKET ST RM 226";
            city = PHILADELPHIA;
            ln = "ESOMEPRAZOLE MAG DR 40 MG CAP";
            ndc = 13668015510;
            npi = 1619912375;
            "pharmacy_name" = "GRACE PHARMACY INC";
            phone = "(215)895-5594";
            price = "74.00";
            quantity = 1000;
            state = PA;
            vendor = una;
            zip = 19104;
        },
{
            address = "1700 Market St";
            brand = G;
            city = Philadelphia;
            distance = "0.22";
            latitude = "39.952981";
            ln = "ESOMEPRAZOLE MAG DR 40 MG CAP";
            longitude = "-75.168431";
            "ncpdp_id" = 3985059;
            ndc = 00378235193;
            "pharmacy_hours_of_operation" = "S(Clsd) M(8a-6p) T(8a-6p) W(8a-6p) T(8a-6p) F(8a-6p) S(9a-12p)";
            "pharmacy_name" = "PICKWICK PHARMACY INC";
            phone = "(215)563-4860";
            price = "241.23";
            quantity = 30;
            state = PA;
            vendor = scriptsave;
            zip = "19103-3913";
        }
    );

====

这是JSON:

quantity

所以在这里,第一个中的Int作为String返回,而import android.location.Address; 则返回到第二个。{{1}}。我开始认为这是服务器方面的问题......

===

在Chrome中查看JSON确认这是来自服务器的编码错误。谢谢@CouchDeveloper

enter image description here

1 个答案:

答案 0 :(得分:1)

Apple的JSONSerialization API对于在Swift中的使用来说有点讨厌。 如果您乐意使用第三方框架,SwiftyJSON将有助于在swift中以类型安全的方式处理JSON。它可以作为Cocoapod使用,使用Carthage甚至是Swift自己的包管理器。

然后,您可以确保获得非零的Integer或String对象,如下所示:

let name = json["name"].stringValue
let number = json["number"].intValue

或者您可以将不存在的值作为选项来处理,如下所示:

let name = json["name"].string
let number = json["number"].int