2017-07-26 69 views
2
{ 
    "item": [ 
     { 
      "pid": 89334, 
      "productsname": "Long Way", 
      "address": "B-4/7, Malikha Housing, Yadanar St., Bawa Myint Ward,", 
      "telephone": "[\"01570269\",\"01572271\"]" 
     }, 
     { 
      "pid": 2, 
      "productsname": "Myanmar Reliance Energy Co., Ltd. (MRE)", 
      "address": "Bldg, 2, Rm# 5, 1st Flr., Hninsi St., ", 
      "telephone": "[\"202916\",\"09-73153580\"]" 
     } 
    ], 
    "success": true 
} 

我無法使用以下代碼從上面的JSON對象解析telephone值。爲什麼SwiftyJSON無法解析快速3中的Array String

for item in swiftyJsonVar["item"].array! { 
    if let jsonDict = item.dictionary { 
     let pid = jsonDict["pid"]!.stringValue 
     let productsname = jsonDict["productsname"]!.stringValue 

     var telephones = [String]() 
     for telephone in (jsonDict["telephone"]?.array)! { 
      telephones.append(telephone.stringValue) 
     } 
    } 
} 

我想要獲取並顯示上述JSON的一個一個電話號碼。我不確定爲什麼上面的代碼不工作。請幫助我如何解決它,謝謝。

回答

4

因爲telephone是一個看起來像一個數組而不是數組本身的字符串。服務器非常嚴格地編碼這個數組。你需要JSON - 如果它再次通過電話號碼列表循環:

for item in swiftyJsonVar["item"].array! { 
    if let jsonDict = item.dictionary { 
     let pid = jsonDict["pid"]!.stringValue 
     let productsname = jsonDict["productsname"]!.stringValue 

     var telephones = [String]() 
     let telephoneData = jsonDict["telephone"]!.stringValue.data(using: .utf8)! 
     let telephoneJSON = JSON(data: telephoneData) 

     for telephone in telephoneJSON.arrayValue { 
      telephones.append(telephone.stringValue) 
     } 
    } 
} 
+0

優秀... !!! – ppshein