2016-09-18 155 views
0

我想解析這個JSON:http://jsonplaceholder.typicode.com/users 我有一個查找JSON結構的問題。 我正在嘗試使用這種結構很好的JSON,但我不確定這是更好的方式還是不行! 解析這個JSON數組到post實例的最好方法是什麼? 有我的代碼:解析JSON數據

func profileFromJSONData(data : NSData) -> ProfileResult { 


     do{ 
     let jsonObject : NSArray! 
    = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSArray 

       for profileJSON in jsonObject { 
        if let profile = profileFromJsonObject(profileJSON as! NSDictionary) { 



         finalProfile.append(profile) 
        } 
       } 

       return .Success(finalProfile) 
      } 
      catch let error { 
       return .Failure(error) 
      } 


     } 



    func profileFromJsonObject(json: NSDictionary) -> UserProfile?{ 

      guard let 
       id = json["id"] as? Int, 
       name = json["name"] as? String, 
       userName = json["username"] as? String, 
       email = json["email"] as? String, 
       address = json["address"] as? NSDictionary, 
       phone = json["phone"] as? String, 
       website = json["website"] as? String, 
       company = json["company"] as? NSDictionary 
       else { 
        return nil 
      } 
      let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company) 

      return obj 
     } 

回答

1

這裏是蘋果的建議時Working with JSON in Swift

,您可以通過使用flatMap

變化提高你的代碼一行從:

for profileJSON in jsonObject { 
    if let profile = profileFromJsonObject(profileJSON) { 
     finalProfile.append(profile) 
    } 
} 

至:

finalProfile += jsonObject.flatMap(profileFromJsonObject) 

這是一樣的。

處理地址:

struct Address { 
    var street: String 
    var city: String 
    ... 
    init?(json: [String: AnyObject]){...} 

} 

extension Address: CustomStringConvertible { 

    var description: String { 

     return "street: \(street), city: \(city)" 
    } 
} 

func profileFromJsonObject(json: [String: AnyObject]) -> UserProfile? { 

    guard let 
      ... 
      addressJson = json["address"] as? [String: AnyObject] 
      address = Address(json: addressJson), 
      ... 
      else { 
       return nil 
     } 

    let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company) 

    print(address) // output: "street: Kulas Light, city: Gwenborough" 

} 
+0

感謝您的建議,所以怎麼能有詳細地址的字符串? – ava

+1

答案更新:您可以將一個屬性'description'添加到'Address',並返回一個可讀的字符串。然後您可以在需要時使用該屬性。這有點像關係數據庫。如果你有使用核心數據,你會發現它行爲像「一對一關係」。 – beeth0ven