用于解析JSON数据的JSON结构

时间:2016-09-15 16:47:37

标签: ios swift nsjsonserialization

我想解析这个JSON,在顶级传入JSON是一个数组,如何访问数组中字典的信息?

    [
      {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "Sincere@april.biz",
        "address": {
          "street": "Kulas Light",
          "suite": "Apt. 556",
          "city": "Gwenborough",
          "zipcode": "92998-3874",
          "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
          }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
          "name": "Romaguera-Crona",
          "catchPhrase": "Multi-layered client-server neural-net",
          "bs": "harness real-time e-markets"
        }
      }
]

这是我的代码,但我不知道如何检测字典数据。

func profileFromJSONData(data : NSData) -> ProfileResult {

        do{
            let jsonObject : [[String:AnyObject]]
            = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [[String:AnyObject]]

            for profileJSON in jsonObject {
                if let profile = profileFromJsonObject(profileJSON) {
                    finalProfile.append(profile)
                }
            }
            return .Success(finalProfile)
        }
        catch let error {
            return .Failure(error)
        }

    }

这是我的profileFromJsonObject方法,用于将JSON解析为配置文件实例

func profileFromJsonObject(json: [String:AnyObject]) -> 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 个答案:

答案 0 :(得分:1)

我在本地文件中尝试了你的JSON,我能够以下面的方式解析模型对象。 您只需将远程JSON放入我的代码中,我希望它能正常工作

func getTheLocalJSON()
{
    let filePath = NSBundle.mainBundle().pathForResource("test", ofType: "json");
    let data = NSData.init(contentsOfFile: filePath!);

    var json : NSArray!
    do{
        json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray;
    }catch{

    }

    print("json \(json)");

    let dictResponse = json.objectAtIndex(0) as! NSDictionary;

    let objUser = profileFromJsonObject(dictResponse)! as UserProfile;

    print("user : \(objUser)");

    //Code to access company name and show it as screen title
    self.title = (objUser.company)!["name"] as? String;

    lblCompanyname.text = (objUser.company)!["name"] as? String;
    lblCatchPhrase.text = (objUser.company)!["catchPhrase"] as? String;
    lblbs.text = (objUser.company)!["bs"] as? String;

}

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
}

输出

enter image description here