2014-11-09 2 views
0

Swift에서 이와 같은 작업을 수행하는 더 좋은 방법이 있습니까?Swift에서 JSON을 처리하는 더 좋은 방법이 있습니까

var jsonError: NSError? 
     let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as NSDictionary 
     if jsonError != nil { 
      return 
     } 

if let threadsArray = jsonDict["threads"] as? NSArray { 
    if let threadInfo = threadsArray[0] as? NSDictionary { 
     if let postsArray = threadInfo["posts"] as? NSArray { 
      if let opPostInfo = postsArray[0] as? NSDictionary { 
       if let filesArray = opPostInfo["files"] as? NSArray { 
        if let firstFileInfo = filesArray[0] as? NSDictionary { 
         if let thumbnail = firstFileInfo["thumbnail"] as? NSString { 
          // ... 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+0

여기에 더 많은 정보를 입력해야한다고 생각합니다. 무엇을하는 더 좋은 방법? – mattias

+0

나는 그 질문이 "나는 그 모든 성가신''''을하지 않고 어떻게 좀 더 예식적인 방식으로 선택자를 다루는가? –

+0

라이브러리를 사용할 수 있습니다. https://github.com/owensd/json-swift가 좋아 보인다. – cncool

답변

2

약간 어쩌면-모나드 - 억양 리팩토링은 도움이 될 수

import Foundation 

let data = NSData(contentsOfFile: "foo.json") 
let jsonDict = NSJSONSerialization.JSONObjectWithData(data!, options:nil, error: nil) as NSDictionary 

func getArray(a: NSArray?, i: Int) -> AnyObject? { 
    return a != nil && i < a!.count ? a![i] : nil; 
} 

func getDict(d: NSDictionary?, i: String) -> AnyObject? { 
    return d != nil ? d![i] : nil; 
} 

func getPath(root: AnyObject?, indices: Array<AnyObject>) -> AnyObject? { 
    var node = root; 
    for (var i = 0; i < indices.count; i++) { 
     if let index = indices[i] as? String { 
      node = getDict(node as NSDictionary?, index); 
     } else if let index = indices[i] as? Int { 
      node = getArray(node as NSArray?, index); 
     } 
    } 

    return node; 
} 

let result = getPath(jsonDict, ["threads", 0, "posts", 0, "files", 0, "thumbnail"]); 
println(result); 
+0

나는이 답변을 정말 좋아합니다. 당신은 세미콜론을 잃을 수 있습니다. – vacawama

+0

@vacawama :) 나는 단지 스위프트를 배우고있다. 나는 수년간 Objective-C를 거쳐야 그 습관을 만들어야합니다. –

1

단지 사물의 JSON 측에 대한 좋은 옵션은 SwiftyJSON을 사용하는 것입니다. 그렇게하면 다음과 같이 쓸 수 있습니다.

let json = JSON(data: data!) 
if let thumb = json["threads"][0]["posts"][0]["files"][0]["thumbnail"].string{ 
    // The ".string" property still produces the correct Optional String type with safety 
} 
관련 문제