【问题标题】:accessing specific value from JSON array swift 4从 JSON 数组 swift 4 访问特定值
【发布时间】:2018-09-30 14:56:23
【问题描述】:

我正在尝试构建一个使用开源 api 的测验应用程序。到目前为止,我已经能够解析 JSON 并使数组全局化。数组作为一个整体打印,但每当我尝试指定一个元素时,我都会收到错误“下标”不可用:无法使用 Int 为字符串下标,请参阅文档注释进行讨论”。

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON

struct Result : Decodable{
    let question : String
    let correct_answer : Bool
}
var r: Result?

class ViewController: UIViewController {
    var r: Result?
        var myResults = [Result]()

    override func viewDidLoad() {
        getQuestionNew()
        super.viewDidLoad()
//        self.r = Result()
        printTest()

    }

        func getQuestionNew(){
            // this is the main screwed up function
            let parameters: Parameters = ["amount": 15, "type":"boolean"]
            Alamofire.request("https://opentdb.com/api.php", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in

//                print("Request: \(String(describing: response.request))")   // original url request
//                print("Response: \(String(describing: response.response))") // http url response
//                print("Result: \(response.result)")



                if((response.result.value) != nil) {
                    let swiftyJsonVar = JSON(response.result.value!)
                    //print(swiftyJsonVar["results"])
                    let results = swiftyJsonVar["results"].arrayValue

                    results.forEach({ (item) in
                        //print("Printing Item \(item["question"].stringValue)")
//                        print("Printing Item ?\(item)")

                        self.r = Result(question: item["question"].stringValue, correct_answer: item["correct_answer"].stringValue == "True" ? true : false)

                        self.myResults.append(self.r!)
                        self.printTest()

//                        print(self.r)
                    })

//                    label.text = allQuestions.list[questionNumber].questionText


                }
            }
        }
    func printTest(){

        //error prone
     print(r?.question[2])
}
}

My code

【问题讨论】:

    标签: arrays json swift xcode scope


    【解决方案1】:

    您的 r?.questionString,而不是 array,因此您收到此错误。据我了解,您需要列表中的问题和答案。如果是,请检查以下代码:

    func printTest(){
            for element in myResults {
                print("Q:", element.question)
                print("A", element.correct_answer)
            }
        }
    

    在 for 循环外调用 printTest():

    results.forEach({ (item) in
                            //print("Printing Item \(item["question"].stringValue)")
    //                        print("Printing Item ?\(item)")
    
                            self.r = Result(question: item["question"].stringValue, correct_answer: item["correct_answer"].stringValue == "True" ? true : false)
    
                            self.myResults.append(self.r!)
                          //  self.printTest()
                        })
           // call here  after loop
          self.printTest()
    

    [编辑 1] 你的完整结构应该如下所示:

    struct Result : Decodable {
        let incorrect_answers : [Bool]?
        let correct_answer : Bool?
        let type : String?
        let category : String?
        let difficulty : String?
        let question : String?
    }
    

    【讨论】:

    • 我实现了您的方法,并将“question”和“correct_aswer”更改为数组,但现在这两个属性的所有值都存储在同一个数组元素下。例如,问题的所有值都在“element.question[0]”下,而“element.question[1]”将导致致命错误。问题的链接是“drive.google.com/drive/folders/…
    • 我无法访问链接。
    • 抱歉,请尝试这个新链接..."drive.google.com/drive/folders/…"
    • 不能改变Decodable结构,应该和你的服务器响应类似。
    • 我实际上不知道如何处理数据,API 链接是“opentdb.com/api.php?amount=15&type=boolean”。能否提供示例代码?
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多