如何使用JSON将数据存储在数组中

时间:2018-08-09 10:21:18

标签: ios json parsing jsonparser

此代码中的一些问题。我无法解决。如何解决?

 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)

            }

        }}

我的api响应是

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

我需要在数组中存储值:-[“是,总是”,“是,有时”,“否”,“我有任何问题”,“其他”]。因此,根据上述功能我写成:-

 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)


                    }

但是在存储选项时有一些问题。如何解决? 在这里,我需要将选项存储在数组中怎么办?

2 个答案:

答案 0 :(得分:0)

data的值是一个数组([[String:Any]] 不是 NSArray),因此您必须迭代该数组

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

但是我建议使用Decodable

将JSON解码为结构
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) }

答案 1 :(得分:0)

使用class vec3 { int x, y, z; public: vec3(int x, int y, int z) : x{x}, y{y}, z{z} {} }; int main() { // Error C2127'up': illegal initialization of 'constexpr' // entity with a non-constant expression constexpr vec3 up{0, 1, 0}; const vec3 up1{0, 1, 0}; } Decodable实体的标准方法

Model

现在设计响应模型

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

现在您的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 } } 回复中

Alamofire