如何在swift 4中使用JSONDecoder从嵌套的JSON中获取数据?

时间:2018-02-01 10:15:25

标签: arrays json xcode jsondecoder

我是swift的新手,首先我想知道编码和解码之间的主要区别。其次,我尝试从响应中获取特定值,如下所示:

enter image description here

我想解码gender_category的值并把它放在piker中,这是我到目前为止所做的:

struct Gender: Decodable {

let result : [Result]

enum CodingKeys :String, CodingKey {
    case result
}

struct Result: Decodable {
    let genderCategory: String


    enum CodingKeys : String, CodingKey {

        case genderCategory = "gender_category"
    }
}
}

我的回复代码是:

 func getGenderValueFromJSON()  {
    let url = URL(string: "http://www.----------.com/GenderList/get")
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error == nil{
            do{

                let result  = try JSONDecoder().decode(Gender.self, from: data!)
                print(result)
            }catch let error as NSError{

                print("Parse Error\(error)")
            }
        }

        }.resume()
}

我以这种方式得到我的结果:

性别(结果:[something.Gender.Result(genderCategory:“Male”),something.Gender.Result(genderCategory:“Female”),something.Gender.Result(genderCategory:“Transgender”),something.Gender .Result(genderCategory:“Others”)])

但是我如何才获得genderCategory的值?

1 个答案:

答案 0 :(得分:2)

resultResult的数组,而不是String

let result : [Result]

这是解码所有键的结构

struct Gender: Decodable {

    let message : String
    let statusCode : Int
    let result : [Result]

    enum CodingKeys :String, CodingKey {
        case message, statusCode = "status_code", result
    }

    struct Result: Decodable {

        let genderCategory: String
        let id : String

        enum CodingKeys : String, CodingKey {
            case genderCategory = "gender_category", id
        }
    }
}

获取gender_category

let gender = try JSONDecoder().decode(Gender.self, from: data!)
for item in gender.result {
    print(item.genderCategory)
}