ios - 解析JSON数据的JSON结构

标签 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
    }

最佳答案

我通过将它放入本地文件来尝试你的 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

关于ios - 解析JSON数据的JSON结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516382/

相关文章:

ios - SwiftUI 2 个问题,但很简单,关于 searchaBle 和 List 的背景图片

ios - 如何从崩溃日志中调试 iOS 设备上的崩溃

swift - 二元运算符 '>' 不能应用于两个 'String?!' 操作数

ios - 拥有可以是任何遵守特定协议(protocol)的对象的属性

ios - 如何使用google api获取用户位置

iOS 从文档目录中高效解析大型 JSON

iphone - 完成按钮仅适用于数字键盘

ios - 使用搜索栏 Swift 3 时出现 fatal error : Index out of range,

swift - 添加嵌套字典导致 JSONSerialization 返回 nil

ios - 使用 NSJSONSerialization 序列化一个 unsigned long long