在swift中如何将JSON响应存储在Model中

brccelvz  于 2022-12-20  发布在  Swift
关注(0)|答案(2)|浏览(119)

我已经为LoginViewController响应创建了模型。
我得到了如下的响应。如何在LoginViewController中向这个模式添加值,我得到了这个响应?

struct Employees: Codable {
    let jsonrpc: String
    let result: Result
}

// MARK: - Result
struct Result: Codable {
    let userdata: Userdata
    let token: String
}

// MARK: - Userdata
struct Userdata: Codable {
    let id: Int
    let fname, lname, email: String
    .......
}

登录视图控制器API调用:

func loginService() {

    let url = URL(string: "https://apkool.com")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   
    let jsonpost = LoginData(jsonrpc: "2.0", params: (PostLogin(email: nameTf.text!, password: passwordTf.text!, device_id: "2")))
        
    do {
        let jsonBody = try JSONEncoder().encode(jsonpost)
        request.httpBody = jsonBody
    } catch {
        print("Error while encoding parameter: \(error)")
    }
    let session = URLSession.shared
    let task = session.dataTask(with: request) { [self] (data, response, error) in
            
        guard let data = data else {return}
            
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
            print("the json output \(String(describing: json))")
            
            let error = json!["error"] as? [String : Any]
            
            let status = error?["status"] as? [String : Any]
                            
            DispatchQueue.main.sync {
                if error != nil {
                    let controller = UIAlertController(title: "Alert", message: "Your email is not verified", preferredStyle: .alert)
                    let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
                    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

                    controller.addAction(ok)
                    controller.addAction(cancel)

                    self.present(controller, animated: true, completion: nil)
                } else {
                
                    let res = json?["result"] as? [String : Any]

                    let uData = res?["userdata"] as? [String : Any]
                    var nameLogin = uData?["slug"] as? String
                    var emailLogin = uData?["email"] as? String
                    print("login name \(String(describing: nameLogin))")
                
                    let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProfileViewController1") as? ProfileViewController1
                    vc?.name = nameLogin
                    vc?.email = emailLogin
                    self.navigationController?.pushViewController(vc!, animated: true) 
                }
            }
            print("the error is \(error)")
        } catch { print("Error while decoding: \(error.localizedDescription)") }
    }
    task.resume()
    
}

**我想添加登录响应到模型中,以便在另一个ViewController中使用这些值。**我在这里卡住了很长时间。请求帮助!

对于上述API,我在登录时得到以下响应:

{
    "jsonrpc": "2.0",
    "result": {
        "userdata": {
            "id": 47,
            "fname": "sample",
            "lname": "test",
            "last_login": "2021-02-23 15:04:56",
            "created_at": "2021-02-17 20:22:49",
            "updated_at": "2021-02-23 15:04:56",
            "deleted_at": null
        },
        "devicetoken": fasfcsdfdsfsdfsd
    }
}
mhd8tkvw

mhd8tkvw1#

由于您可能会从服务器收到如下错误:

{
   "jsonrpc": "2.0",
   "error": {
       "status": {
           "code": "-32706",
           "message": "Not Verified",
           "meaning": "Your email is not verified."
      }
   }
}

改变你的模型:

struct Employees: Codable {
    let jsonrpc:String
    let result:Result?
    let error:ResponseError?
}

struct ResponseError:Codable {
    let status:ErrorStatus
}

struct ErrorStatus:Codable {
    let code:String?
    let message:String?
    let meaning:String?
}

// MARK: - Result
struct Result: Codable {
    let userdata: Userdata
    let token: String
}
  
// MARK: - Userdata
struct Userdata: Codable {
let id: Int
let fname, lname, slug, email: String
......

//IMPORTANT: MAKE SURE YOUR CONSTANT NAMES ARE EXACTLY THE SAME AS YOUR 
            //RESPONSE, OTHERWISE YOU MUST ADD AN ENUM like so: 

private enum CodingKeys: String, CodingKey {
        case firstName = "fname"
}

那么在你的API中

func loginService(){
        
        let url = URL(string: "https://appleskool.com/preview/appleskool_code/api/login")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let jsonpost = LoginData(jsonrpc: "2.0", params: (PostLogin(email: nameTf.text!, password: passwordTf.text!, device_id: "2")))
        
    let session = URLSession.shared
    let task = session.dataTask(with: request) { [self] (data, response, error) in
        guard let data = data else {return}
        let decoder = JSONDecoder()
        guard let employees = try? decoder.decode(Employees.self, from: data) else { return }
        //then you can access your result
        if let error = employees.error {
            //use your error
            print(error.status.message)
            print(error.status.meaning)
        }else{
            //use your data
            guard let user = employees.result else {return }
            print(user.userdata.fname)
            print(user.userdata.lname)
            print(user.userdata.email)
            print(user.userdata.slug)
            // or your can do what you already doing in your code 
            let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProfileViewController1") as? ProfileViewController1
            vc?.name = ser.userdata.fname
            vc?.lastName = ser.userdata.lname
            //if you want to pass the token
            vc?.token = user.token
            self.navigationController?.pushViewController(vc!, animated: true)
            // etc
        }
    }
    task.resume()
}
hsvhsicv

hsvhsicv2#

// MARK: - LoginModel
class LoginModel: Codable {
    var jsonrpc: String?
    var result: Result?

    init(jsonrpc: String?, result: Result?) {
        self.jsonrpc = jsonrpc
        self.result = result
    }
}

// MARK: - Result
class Result: Codable {
    var userdata: Userdata?
    var token: String?

    init(userdata: Userdata?, token: String?) {
        self.userdata = userdata
        self.token = token
    }
}

// MARK: - Userdata
class Userdata: Codable {
    var id: Int?
    var fname, lname, slug, email: String?
    var emailVcode, rememberToken, nickName: JSONNull?
    var userType, isFeatured, emailVerifiedAt, password: String?
    var phoneCountryCode: JSONNull?
    var phoneNo: String?
    var providerID: JSONNull?
    var providerName, registrationType, deviceID: String?
    var token: JSONNull?
    var status: String?
    var gender: JSONNull?
    var isInstitute: String?
    var instituteCertificate, isCertificateApproved, dob: JSONNull?
    var hourlyRate: String?
    var street: JSONNull?
    var countryID: String?
    var state, city, pin, profilePicture: JSONNull?
    var experience, aboutMeShrt, aboutMe, video: JSONNull?
    var occupationID, educationID, industryID, youtubeLink: JSONNull?
    var twitterLink, facebookLink, blogsLink, websiteLink: JSONNull?
    var bankName, accountNo, ifscCode, accountHolderName: JSONNull?
    var walletBalance: String?
    var degreeCertificate, certificateUploadedAt, officialLink, totalRating: JSONNull?
    var avgRating: JSONNull?
    var memberShipType: String?
    var memberShipAmount, validTill: JSONNull?
    var lastLogin, createdAt, updatedAt: String?
    var deletedAt: JSONNull?

    enum CodingKeys: String, CodingKey {
        case id, fname, lname, slug, email
        case emailVcode = "email_vcode"
        case rememberToken = "remember_token"
        case nickName = "nick_name"
        case userType = "user_type"
        case isFeatured = "is_featured"
        case emailVerifiedAt = "email_verified_at"
        case password
        case phoneCountryCode = "phone_country_code"
        case phoneNo = "phone_no"
        case providerID = "provider_id"
        case providerName = "provider_name"
        case registrationType = "registration_type"
        case deviceID = "device_id"
        case token, status, gender
        case isInstitute = "is_institute"
        case instituteCertificate = "institute_certificate"
        case isCertificateApproved = "is_certificate_approved"
        case dob
        case hourlyRate = "hourly_rate"
        case street
        case countryID = "country_id"
        case state, city, pin
        case profilePicture = "profile_picture"
        case experience
        case aboutMeShrt = "about_me_shrt"
        case aboutMe = "about_me"
        case video
        case occupationID = "occupation_id"
        case educationID = "education_id"
        case industryID = "industry_id"
        case youtubeLink = "youtube_link"
        case twitterLink = "twitter_link"
        case facebookLink = "facebook_link"
        case blogsLink = "blogs_link"
        case websiteLink = "website_link"
        case bankName = "bank_name"
        case accountNo = "account_no"
        case ifscCode = "ifsc_code"
        case accountHolderName = "account_holder_name"
        case walletBalance = "wallet_balance"
        case degreeCertificate = "degree_certificate"
        case certificateUploadedAt = "certificate_uploaded_at"
        case officialLink = "official_link"
        case totalRating = "total_rating"
        case avgRating = "avg_rating"
        case memberShipType = "member_ship_type"
        case memberShipAmount = "member_ship_amount"
        case validTill = "valid_till"
        case lastLogin = "last_login"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case deletedAt = "deleted_at"
    }

    init(id: Int?, fname: String?, lname: String?, slug: String?, email: String?, emailVcode: JSONNull?, rememberToken: JSONNull?, nickName: JSONNull?, userType: String?, isFeatured: String?, emailVerifiedAt: String?, password: String?, phoneCountryCode: JSONNull?, phoneNo: String?, providerID: JSONNull?, providerName: String?, registrationType: String?, deviceID: String?, token: JSONNull?, status: String?, gender: JSONNull?, isInstitute: String?, instituteCertificate: JSONNull?, isCertificateApproved: JSONNull?, dob: JSONNull?, hourlyRate: String?, street: JSONNull?, countryID: String?, state: JSONNull?, city: JSONNull?, pin: JSONNull?, profilePicture: JSONNull?, experience: JSONNull?, aboutMeShrt: JSONNull?, aboutMe: JSONNull?, video: JSONNull?, occupationID: JSONNull?, educationID: JSONNull?, industryID: JSONNull?, youtubeLink: JSONNull?, twitterLink: JSONNull?, facebookLink: JSONNull?, blogsLink: JSONNull?, websiteLink: JSONNull?, bankName: JSONNull?, accountNo: JSONNull?, ifscCode: JSONNull?, accountHolderName: JSONNull?, walletBalance: String?, degreeCertificate: JSONNull?, certificateUploadedAt: JSONNull?, officialLink: JSONNull?, totalRating: JSONNull?, avgRating: JSONNull?, memberShipType: String?, memberShipAmount: JSONNull?, validTill: JSONNull?, lastLogin: String?, createdAt: String?, updatedAt: String?, deletedAt: JSONNull?) {
        self.id = id
        self.fname = fname
        self.lname = lname
        self.slug = slug
        self.email = email
        self.emailVcode = emailVcode
        self.rememberToken = rememberToken
        self.nickName = nickName
        self.userType = userType
        self.isFeatured = isFeatured
        self.emailVerifiedAt = emailVerifiedAt
        self.password = password
        self.phoneCountryCode = phoneCountryCode
        self.phoneNo = phoneNo
        self.providerID = providerID
        self.providerName = providerName
        self.registrationType = registrationType
        self.deviceID = deviceID
        self.token = token
        self.status = status
        self.gender = gender
        self.isInstitute = isInstitute
        self.instituteCertificate = instituteCertificate
        self.isCertificateApproved = isCertificateApproved
        self.dob = dob
        self.hourlyRate = hourlyRate
        self.street = street
        self.countryID = countryID
        self.state = state
        self.city = city
        self.pin = pin
        self.profilePicture = profilePicture
        self.experience = experience
        self.aboutMeShrt = aboutMeShrt
        self.aboutMe = aboutMe
        self.video = video
        self.occupationID = occupationID
        self.educationID = educationID
        self.industryID = industryID
        self.youtubeLink = youtubeLink
        self.twitterLink = twitterLink
        self.facebookLink = facebookLink
        self.blogsLink = blogsLink
        self.websiteLink = websiteLink
        self.bankName = bankName
        self.accountNo = accountNo
        self.ifscCode = ifscCode
        self.accountHolderName = accountHolderName
        self.walletBalance = walletBalance
        self.degreeCertificate = degreeCertificate
        self.certificateUploadedAt = certificateUploadedAt
        self.officialLink = officialLink
        self.totalRating = totalRating
        self.avgRating = avgRating
        self.memberShipType = memberShipType
        self.memberShipAmount = memberShipAmount
        self.validTill = validTill
        self.lastLogin = lastLogin
        self.createdAt = createdAt
        self.updatedAt = updatedAt
        self.deletedAt = deletedAt
    }
}

// MARK: - Encode/decode helpers

class JSONNull: Codable, Hashable {

    public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
        return true
    }

    public var hashValue: Int {
        return 0
    }

    public func hash(into hasher: inout Hasher) {
        // No-op
    }

    public init() {}

    public required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if !container.decodeNil() {
            throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encodeNil()
    }
}

你可以试试这个模型,你可以解码你的数据如下。这里的数据是从你的guardlet语句的响应。

do {
    let model = try JSONDecoder().decode(LoginModel.self, from: data)
} catch {
  debugPrint(error)
}

相关问题