2016-01-26 101 views
2

我正在運行我認爲是一個錯誤。我有一個從服務器返回的對象數組。但是,當從他們中拉出數值時,我會得到不一致的結果。所有這些項目都是從服務器的響應的同一陣列中:解析快速不一致的JSON

當我試圖去拉這一個返回在Intquantity值:

{ 
    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"; 
} 

爲什麼世界上會發生這種情況?兩個對象似乎是相同的,除了一個額外的值。

===

序列化這樣的JSON:

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

抓取的值是這樣的:

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

====

這裏是JSON:

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"; 
     } 
    ); 

因此,第一個中的quantity作爲Int返回,並且作爲String返回到第二個中。我開始認爲這是一個服務器端的問題...

===

望着JSON在Chrome並確認它是來自服務器的編碼錯誤。由於@CouchDeveloper

enter image description here

+0

什麼代碼是你用來獲取數量值? – Jeremiah

+0

你用什麼來解析JSON? –

+0

@TahTatsumoto我已經更新了我的問題。謝謝你的快速反應。 – random

回答

1

蘋果的API對JSONSerialization是在斯威夫特的使用有點討厭。 如果您樂意使用第三方框架,SwiftyJSON將以類型安全的方式快速處理JSON。它可以作爲Cocoapod使用,使用Carthage或Swift自己的軟件包管理器。

然後,您可以確保您獲得非零整數或String對象,像這樣:

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

或者你可以處理不存在的值作爲自選就像這樣:

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

如果我無法得到任何其他工作,我會給它一個鏡頭。我很感激!! – random