将json输出解码为模型 [英] Decode json output to a model

查看:130
本文介绍了将json输出解码为模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个要使用Codable解析的json输出:

I have this json output that I want to parse using Codable:

{
"success": true,
"total": 1,
"users": [
    {
        "user": {
            "id": "1",
            "fname": "admin",
            "lname": "admin",
            "login": "admin",
            "actif": "0",
            "last_connection_date": "2018-01-18 16:02:34"
        }
    }
],
"msg": ""
}

我只想从中提取用户的信息. 我的用户的模型

And I just want to exctact the user's informations out of it. My user's model

import RealmSwift

class User: Object, Codable {

@objc dynamic var id: String = ""
@objc dynamic var fname: String = ""
@objc dynamic var lname: String = ""
@objc dynamic var login: String = ""

//    private enum CodingKeys : String, CodingKey {
//        case id = "users[0].user.id"
//        case fname = "users[0].user.fname"
//        case lname = "users[0].lname"
//        case login = "users[0].user.login"
//        case password = "users[0].user.password"
//    }

}

// Somewhere in my code
Alamofire.request(Path.userInformations(id: userId).rawValue).
responseJSON(completionHandler: { response in
       do {
            let user = try JSONDecoder().decode(User.self, from: response.data!)
            } catch (let error) {
                print(error.localizedDescription)
            }
       })

我尝试提取用户的对象,但未成功将其强制转换为Data以便将其提供给JSONDecoder().decode()方法.

I've tried extracting the user's object, but wasn't successful casting it to Data to feed it to JSONDecoder().decode() method.

我已经尝试过您的第一种方法.它似乎不起作用,因为我认为在用户对象之前输入了关键字"user".我尝试添加一个新结构来包装用户的对象,但是并不能解决问题.

I've tried you first approach. It does not seem to work because, I think, of keyword "user" before the user's object. I've tried adding a new struct that wrap the user's object, but does not solve it.

struct ResponseBody : Codable {
   var success : Bool?
   var total : Int?
   var users : [UserHolder]?
   var msg : String?
   var query_start : String?
   var query_end : String?
   var query_time : String?
   var paging : Bool?
}

struct UserHolder : Codable {
    var user: User?

    enum CodingKeys: String, CodingKey {

        case user = "user"

    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        user = try values.decodeIfPresent(User.self, forKey: .user)
    }
}

推荐答案

我认为您的响应类结构应类似于:

I think your response class structure should be like:

import Foundation
struct ResponseBody : Codable {
var status : Bool?
var total : Int?
var users : [User]? //list of users 
var msg : String?

enum CodingKeys: String, CodingKey {

    case status = "status"
    case total = "total"
    case users = "users"
    case msg = "msg"
}

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    status = try values.decodeIfPresent(Bool.self, forKey: . status)
    total = try values.decodeIfPresent(Int.self, forKey: . total)
    users = try values.decodeIfPresent([User].self, forKey: . users)
    msg = try values.decodeIfPresent(String.self, forKey: . msg)
}
}

现在您将能够检索到对象的JSON数据

Now you will able to retrive your JSON data to object

let jsonDecoder = JSONDecoder()
let response = try jsonDecoder.decode(ResponseBody.self, from: data)

for user in response.users {
   // user object is here
}

#edit

如果您不想解析对JSON对象的完整响应

If you do not want to parse full response to JSON object

  1. 首先使用

  1. First convert Data to JSON Object using

让jsonResponse =试试JSONSerialization.jsonObject(with:data,options:.mutableContainers)为!字典

let jsonResponse = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! Dictionary

获取用户列表字符串JSON,然后将其转换为Data,然后将其转换为User List对象

Get users list string JSON then convert it to Data and after that data to User List object

如果让responseBody = jsonResponse ["users"] {

if let responseBody = jsonResponse["users"] {

let dataBody =(responseBody as!字符串).data(使用:.utf8)! 如果让obj = Utils.convertToArray(data:dataBody){ print(obj)//用户obj的列表 } }

let dataBody = (responseBody as! String).data(using: .utf8)! if let obj = Utils.convertToArray(data: dataBody) { print(obj) // list of user obj } }

听是上述实现中使用的方法

Hear is the method using in above implementation

class func convertToArray(data: Data) -> [AnyObject]? {
    do {
        return try JSONSerialization.jsonObject(with: data, options: []) as? [AnyObject]
    } catch {
        Constants.print(items: error.localizedDescription)
    }
    return nil
}

希望这对您有所帮助.快乐的编码:)

Hope this help you. Happy codding :)

因此,您可以听到适合的工作代码 在我的游乐场上一切正常.请查看下面的屏幕截图

So hear is the working code for you It's just working fine in my Playground. Please see below screenshots

1.

2.

3.

将json输出解码为模型

结果:

这篇关于将json输出解码为模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆