我的Swift代码无法将JSON解码为结构

时间:2017-12-11 05:45:35

标签: json swift struct

我有一个页面显示我的用户信息,我想让用户能够更新信息。所以我创建了一个更新按钮,然后如果用户按下该按钮,它会将信息发送到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很新吗?

1 个答案:

答案 0 :(得分:1)

请阅读JSON,所有字符串都用双引号括起来,heightweightageString,而不是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
    }
}