如何将复杂的json转换为swift中的某个对象

时间:2016-07-11 15:43:41

标签: ios json swift serialization nsjsonserialization

在我的iphone应用程序中,我必须连接到我的服务器脚本才能从数据库中获取一些数据。我得到一些字符串格式的json,如下所示:

[
    {   
        "id":4,
        "title":"Lokacija 03",
        "address":"Zagreba\u010dka 777",
        "place":"Rijeka","post":"51000",
        "pivot": {
                    "user_id":"7",
                    "location_id":"4"
                 }
    },
    {
        "id":3,
        "title":"Lokacija 11",
        "address":"Adresica 111",
        "place":"Zagreb",
        "post":"10000",
        "pivot": {
                    "user_id":"7",
                    "location_id":"3"
                 }
    }
]

我尝试使用此功能将其转换为字典,但未成功:

func convertStringToDictionary2(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
        return json
    } catch {
        print("Something went wrong")
    }
}
return nil

}

我尝试将其转换为字典。如果你有更好的方法(其他一些对象等),我将非常感激。

0 个答案:

没有答案