有没有更好的方法来处理Swift中的JSON

时间:2014-11-09 08:34:13

标签: swift

有没有更好的办法在Swift中做这样的事情?

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 {
                            // ...
                        }
                    }
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

一点点可能是monad-esque的重构可能会有所帮助:

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);

答案 1 :(得分: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
}