2017-02-07 44 views
3

我試圖解析JSON是像下面如何解析JSON數組到陣列中的斯威夫特

[ 
    { 
    "People": [ 
        "Jack", 
        "Jones", 
        "Rock", 
        "Taylor", 
        "Rob" 
        ] 
    }, 
    { 
    "People": [ 
      "Rose", 
      "John" 

     ] 
     }, 
     { 
     "People": [ 
      "Ted" 
     ] 
     } 
] 

而導致該[「傑克」的數組,「瓊斯」,「搖滾」 ,「泰勒」,「羅布」],[「玫瑰」,「約翰」],[「泰德」]]

這是陣列的數組。

我的代碼試圖下面

if let path = Bundle.main.path(forResource: "People", ofType: "json") 
     { 

      let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [AnyObject] 
      for people in peoplesArray! { 
       print(people) 
      } 

     } 

當我打印的「人」,我得到O/P爲

{ 
    People =  (
     Jack, 
     "Jones", 
     "Rock", 
     "Taylor", 
     "Rob" 
    ); 
} 
{ 
    People =  (
     "Rose", 
     "John" 
    ); 
} 
..... 

我很困惑如何解析的時候已經「人」重複3它次

試圖顯示在UITableView的內容在我的第一小區有「傑克」「搶」和第二單元有「玫瑰」,「約翰」和第三單元爲「泰德」

請幫助我理解如何實現這一點

回答

3
var peoplesArray:[Any] = [ 
    [ 
     "People": [ 
     "Jack", 
     "Jones", 
     "Rock", 
     "Taylor", 
     "Rob" 
     ] 
    ], 
    [ 
     "People": [ 
     "Rose", 
     "John" 

     ] 
    ], 
    [ 
     "People": [ 
     "Ted" 
     ] 
    ] 
    ] 

var finalArray:[Any] = [] 

for peopleDict in peoplesArray { 
    if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] { 
     finalArray.append(peopleArray) 
    } 
} 

print(finalArray) 

輸出:

[["Jack", "Jones", "Rock", "Taylor", "Rob"], ["Rose", "John"], ["Ted"]] 

你的情況,這將是:

if let path = Bundle.main.path(forResource: "People", ofType: "json") { 
    let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [Any] 

    var finalArray:[Any] = [] 

    for peopleDict in peoplesArray { 
     if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] { 
      finalArray.append(peopleArray) 
     } 
    } 

    print(finalArray) 
} 
0

你在這裏有什麼是第一個數組的3個對象。每個對象都是一個字典,其中鍵是人,值是一個字符串數組。當你試圖執行jsonserialization時,你必須將其轉換爲預期的結果。所以,你必須首先對象的數組,然後你有一個字符串的字典:任何,那麼你得到的字符串

let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as? [AnyObject] 
    guard let peoplesObject = peoplesArray["people"] as? [[String:Any]] else { return } 
    for people in peoplesObject { 
    print("\(people)") 
} 
+0

我得到零在peoplesObject時,即時通訊執行..我的JSON是正確的,但不知道爲什麼 – Ashh

+0

你有你的應用程序內的JSON或者你得到它作爲來自網絡的響應?你可能會因爲這個而變成零!從嘗試,但我不知道 – anckydocky

+0

看,這是我如何設法解析來自LastFM的JSON響應的一個例子 – anckydocky

0

我不能評論粘貼它的數組,實在是太長了什麼

static func photosFromJSONObject(data: Data) -> photosResult { 
    do { 
     let jsonObject : Any = 
      try JSONSerialization.jsonObject(with: data, options: []) 

     print(jsonObject) 

     guard let 
      jsonDictionary = jsonObject as? [NSObject : Any] as NSDictionary?, 
      let trackObject = jsonDictionary["track"] as? [String : Any], 
      let album = trackObject["album"] as? [String : Any], 
      let photosArray = album["image"] as? [[String : Any]] 

      else { return .failure(lastFMError.invalidJSONData) } 
} 

並且json是這樣的:

{ 
    artist: { 
    name: Cher, 
    track: { 
     title: WhateverTitle, 
     album: { 
      title: AlbumWhatever, 
      image: { 
      small: "image.px", 
      medium: "image.2px", 
      large: "image.3px"} 
     .... 
0

讓我們假設JSON是編碼數據

var arrayOfData : [String] = [] 
    dispatch_async(dispatch_get_main_queue(),{ 
    for data in json as! [Dictionary<String,AnyObject>] 
    { 
    let data1 = data["People"] 

    arrayOfData.append(data1!) 
    } 
    }) 

您現在可以使用arrayOfData。 :d

2

您可以在優雅的和類型安全的方式利用斯威夫特4 Decodable

首先定義你的人數組類型做到這一點。

struct People { 
    let names: [String] 
} 

然後讓它Decodable,以便它可以用JSON初始化。

extension People: Decodable { 

    private enum Key: String, CodingKey { 
    case names = "People" 
    } 

    init(from decoder: Decoder) throws { 
    let container = try decoder.container(keyedBy: Key.self) 

    self.names = try container.decode([String].self, forKey: .names) 
    } 
} 

現在您可以輕鬆解碼你的JSON輸入

guard 
    let url = Bundle.main.url(forResource: "People", withExtension: "json"), 
    let data = try? Data(contentsOf: url) 
else { /* Insert error handling here */ } 

do { 
    let people = try JSONDecoder().decode([People].self, from: data) 
} catch { 
    // I find it handy to keep track of why the decoding has failed. E.g.: 
    print(error) 
    // Insert error handling here 
} 

最後獲得獲得名的你線性陣列,你可以做

let names = people.flatMap { $0.names } 
// => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]