2016-09-18 3 views
0

구문 분석하고자합니다. JSON : http://jsonplaceholder.typicode.com/users JSON 구조를 찾을 때 문제가 있습니다. 잘 작동하는이 구조로 JSON을 시도하고 있지만이 방법이 더 좋은지 또는 그렇지 않은지 잘 모르겠습니다. 이 JSON 배열을 파싱하여 인스턴스를 게시하는 가장 좋은 방법은 무엇입니까? 내 코드가있다 :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

답변이 업데이트되었습니다 :'Address' 속성에'description' 속성을 추가하고 읽을 수있는 문자열을 반환 할 수 있습니다. 필요할 때 속성을 사용할 수 있습니다. 이것은 관계형 데이터베이스와 비슷합니다. 핵심 데이터를 사용하면 '한 관계로'와 같은 역할을합니다. – beeth0ven