-2

Some problem in this code.I can 't able to solve .How to solve it?

 func loadFromWebserviceData(completion :@escaping (DataSourceModel?) -> ()){


        Alamofire.request("http://www.example.com").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON{ response in


            print(response)

            switch response.result{


            case .success(let data):
                print("success",data)


                let result = response.result

                print(result)

                if     let wholedata = result.value as? [String:Any]{

                    print(wholedata)


                    let data1 = wholedata["data"] as? NSArray
                    print(data)
                  let  array = data1["options"] as? [String:Any]
                  print(array)


                    if  let data = wholedata["data"] as? Array<[String:Any]>{

                        print(data)
                        print(response)




                        let newDataSource:DataSourceModel = NH_QuestionDataSourceModel(array: data)

                        completion(newDataSource)


                    }



                }


            case .failure(let encodingError ):
                print(encodingError)

                //  if response.response?.statusCode == 404{

                print(encodingError.localizedDescription)

                completion(nil)

            }

        }}

and my api response is

{
  "data": [
    {
      "id": 35,
      "question": "How ARE u?",
      "options": [
        "Yes, always",
        "Yes, sometimes",
        "No",
        "I did have any questions",
        "Other"
      ],
      "button_type": "2",
      "option_count": "5"
    }
  ]
}

I need to store the values:-["Yes, always","Yes, sometimes","No","I did have any questions","Other"] in the array .So according to the above function i have written as:-

 case .success(let data):
                print("success",data)


                let result = response.result

                print(result)

                if     let wholedata = result.value as? [String:Any]{

                    print(wholedata)




                    if  let data = wholedata["data"] as? Array<[String:Any]>{

                        print(data)
                        print(response)

                  let options = data["options"] as? [String]
                  print(options)


                        let newDataSource:NH_QuestionDataSourceModel = NH_QuestionDataSourceModel(array: data)

                        completion(newDataSource)


                    }

But while storing in options some problems.How to solve it? Here i need to store options in an array how to do?

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – andesta.erfan Aug 09 '18 at 10:27

2 Answers2

0

The value for key data is an array ([[String:Any]] not NSArray) so you have to iterate the array

if let data1 = wholedata["data"] as? [[String:Any]] {
    for question in data1 {
        let options = question["options"] as! [String]
        print(options)
    }
}

However I recommend to decode the JSON into structs with Decodable

let jsonString = """
{"data":[{"id":35,"question":"How ARE u?","options":["Yes, always","Yes, sometimes","No","I did have any questions","Other"],"button_type":"2","option_count":"5"}]}
"""

struct Response : Decodable {
    let data: [Question]
}

struct Question: Decodable {
    let id: Int
    let question: String
    let options: [String]
    let buttonType, optionCount: String
}


let data = Data(jsonString.utf8)
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let result = try decoder.decode(Response.self, from: data)
    print(result.data)
} catch { print(error) }
vadian
  • 274,689
  • 30
  • 353
  • 361
0

The standard way to using Decodable & Model entity

class QuestionSetModel: Decodable {
    var id: Int?
    var question: String?
    var options: [String]?
    var buttonType: Int?
    var optionCount: Int?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case question = "question"
        case options = "options"
        case buttonType = "button_type"
        case optionCount = "option_count"
    }

    required init(with decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = (try? container.decodeIfPresent(Int.self, .id)) ?? nil
        question = (try? container.decodeIfPresent(String.self, .question)) ?? nil
        options = (try? container.decodeIfPresent([String].self), .options) ?? nil
        buttonType = (try? container.decodeIfPresent(Int.self, .buttonType)) ?? nil
        optionCount = (try? container.decodeIfPresent(Int.self, .optionCount)) ?? nil
    }
}

Now Design the response model

class QuestionSetResponseModel: Decodable {
     var data: [QuestionSetModel]?
     enum CodingKeys: String, CodingKey {
         case data
     }
     required init(with decoder: Decoder) throws {
         let container = try decoder.container(keyedBy: CodingKeys.self)
         data = (try? container.decodeIfPresent([QuestionSetModel].self, forKey: .data)) ?? nil
     }
}

Now in your Alamofire response

// here you receive the response
switch result.response.statusCode {
case 200?:
       if let data = result.data,
          let questionResponse = try? JSONDecoder().decode(QuestionSetResponseModel.self,
                                                                          from: data) {

         // here you can access all the thing
         if let questions = questionResponse.data {
             for question in questions {
                 // here you got your question
                 if let options = question.options {
                    for option in options {
                        // here you get your options
                    }
                 }
             }
         }
  }
default:
       print("status code error")
}
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44