【问题标题】:My Swift code can not decode the JSON to structure我的 Swift 代码无法将 JSON 解码为结构
【发布时间】:2017-12-11 05:45:35
【问题描述】:

我有一个显示我的用户信息的页面,我想让用户能够更新信息。所以我创建了一个更新按钮,然后如果用户按下该按钮,它会将信息发送到 API 并获取一个 json 作为新值。我的问题是我无法将该 json 解码为我的结构。 这是我发送数据的方式:

     var user: Update?
    @IBAction func save_user_info_action(_ sender: UIButton) {
     var me = Me()
    let user_credentials = UserDefaults.standard
    guard let id = user_credentials.value(forKey: userDefaults_info.id.rawValue) else {return}


    let username = self.username_txt.text
    let fullname = self.fullName_txt.text
    let email = self.email_txt.text
    let sex = self.sex_txt.text
    let height = self.height_txt.text
    let weight = self.wight_txt.text
    let age = self.age_txt.text
    let password = self.password_txt.text

    if (username != "" && fullname != "" && email != "" && sex != "" && height != "" && weight != ""){

        let url = URL(string: "\(API.user_info_update.rawValue)\(id)")!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "PUT"
        let postString = "user_name=\(username!)&email=\(email!)&password=\(password!)&sex=\(sex!)&height=\(height!)&weight=\(weight!)&age=\(age!)&full_name=\(fullname!)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in


            guard let data = data, error == nil else {
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("\(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print(responseString!)

            guard var result = responseString else { return }


            if let json = try? JSONDecoder().decode(Update.self, from: data){
               self.user = json

                print("username : \(self.user?.userID)")



            }

        }
        task.resume()

结果我得到以下 JSON ==>

{"user_id":13,"email":"jhx@gmail.com","password":"pass","user_name":"jhx","full_name":"no name","sex":"no sex","height":"0","weight":"0","age":"","score":0,"createdAt":"2017-12-10T05:18:42.000Z","updatedAt":"2017-12-11T05:36:58.000Z"}

这也是我想将 json 解码为 ==> 的结构

import UIKit

struct Update: Codable { 


    let userID : Int?
    let email : String?
    let password : String?
    let userName : String?
    var fullName:String?
    var sex:String?
    var height:Int?
    var weight:Int?
    var age:Int?
    var score : Int?
    var createdAt:String?
    var updatedAt:String?



    func getUserID () -> Int {
        return self.userID!
    }
    func getScore () -> Int {
        return self.score!
    }


    func getEmail () -> String {
        return self.email!
    }
    func getPassword () -> String {
        return self.password!
    }

    func getUsername () -> String {
        return self.userName!
    }


    func getFullname () -> String {
        return self.fullName!
    }

    func getSex () -> String {
        return self.sex!
    }

    func getHeight () -> Int{
        return self.height!
    }

    func getWeight () -> Int{
        return self.weight!
    }



    func getCreatedAt () -> String {
        return self.createdAt!
    }




    enum CodingKeys: String, CodingKey {
        case userID = "user_id"
        case email
        case password
        case score
        case userName = "user_name"
        case fullName = "full_name"
        case sex
        case height
        case weight
        case age
        case createdAt
        case updatedAt
    }


}

但它不起作用。我试图调试它,似乎在我有if let json = try? JSONDecoder().decode(Update.self, from: data){ 的那一行,程序永远不会进入 if 语句。知道我在哪里犯错了吗?我该如何解决?我对 swift 中的 JSON 很陌生?

【问题讨论】:

  • 打印什么:print(responseString!) ?
  • 不要声明结构属性变量,而是将它们声明为常量,并在需要更改时使用新值创建一个新对象。
  • 我已经用它在我的控制台中获取接收到的 json,一旦我可以得到结果,我可以删除它
  • 他问JSON响应是什么
  • {"user_id":13,"email":"jhx@gmail.com","password":"pass","user_name":"jhx","full_name":"no name","sex":"no sex","height":"0","weight":"0","age":"","score":0,"createdAt":"2017-12-10T05:18:42.000Z","updatedAt":"2017-12-11T06:05:56.000Z"}

标签: json swift struct


【解决方案1】:

请阅读 JSON,所有字符串都用双引号括起来,所以 height、weight 和 age 是 String,而不是 Int。

这个结构就足够了。如果您将所有属性声明为非可选,则这些函数是多余的

struct Update: Codable {

    enum Sex : Codable, String {
        case female, male, noSex = "no sex"
    }

    let userID: Int
    let email: String
    let password: String
    let userName: String
    let fullName: String
    let sex: Sex
    let height: String
    let weight: String
    let age: String
    let score: Int
    let createdAt: String
    let updatedAt: String

    enum CodingKeys: String, CodingKey {
        case userID = "user_id"
        case email, password, score
        case userName = "user_name"
        case fullName = "full_name"
        case sex, height, weight, age, createdAt, updatedAt
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2014-01-18
    • 2016-10-09
    相关资源
    最近更新 更多