2014-11-09 42 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 2014-11-09 08:36:35

+0

我想这个问题是:“我如何以一种更优雅的方式来处理可选项,而不是做所有那些讨厌的'如果'”? – 2014-11-09 08:38:08

+0

你可以使用一个库。 https://github.com/owensd/json-swift看起来不错。 – cncool 2014-11-09 08:38:30

回答

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 2014-11-09 14:49:47

+0

@vacawama :)我刚刚学习斯威夫特。在Objective-C多年之后,我仍然需要养成这种习惯。 – 2014-11-09 15:56:46

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 
} 
相关问题