簡體   English   中英

用於解析JSON數據的JSON結構

[英]JSON Structure for parsing JSON data

我想解析此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
    }

我通過將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
}

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM