0

I am very new in swift, first of all I want to know what is the major difference between Encoding and Decoding. Secondly, I am try to get a particular value from the response as shown below:

enter image description here

I want to decode the value of gender_category and put it in piker, here is what i have done till now:

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"
    }
}
}

And my code to get response is this:

 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()
}

I get my result in this way:

Gender(result: [something.Gender.Result(genderCategory: "Male"), something.Gender.Result(genderCategory: "Female"), something.Gender.Result(genderCategory: "Transgender"), something.Gender.Result(genderCategory: "Others")])

But how do I get only the value of genderCategory?

TheSwiftGuy77
  • 656
  • 1
  • 9
  • 25
  • `let result : [String]` You mean `let result : [Result]`? Because `result` is an array of dict, not an array of string, so when you read it (decode), you get your issue. – Larme Feb 01 '18 at 10:19
  • thats a type miss match, its let result : [Result], i have done to too but i want an actual answer for it – TheSwiftGuy77 Feb 01 '18 at 10:23

1 Answers1

2

result is an array of Result, not String

let result : [Result]

This are the structs decoding all keys

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
        }
    }
}

To get the gender_category values

let gender = try JSONDecoder().decode(Gender.self, from: data!)
for item in gender.result {
    print(item.genderCategory)
}
vadian
  • 274,689
  • 30
  • 353
  • 361