Writing JSON file programmatically swift

前端 未结 3 1957
青春惊慌失措
青春惊慌失措 2021-01-07 12:04

im making quiz app and I want to download questions from server in JSON file, parse it and make question object that I will present. I did it so now I want to make an app th

3条回答
  •  执念已碎
    2021-01-07 12:36

    Try this Playground file

    Swift 3

    let jsonString = "[" +
        "{" +
        "    \"question\":\"If you want to create a custom class which can be displayed on the view, you can subclass UIView.\"," +
        "    \"answers\":[\"True\", \"False\"]," +
        "    \"correctIndex\":0," +
        "    \"module\":3," +
        "    \"lesson\":0," +
        "    \"feedback\":\"Subclassing UIView gives your class the methods and properties of a basic view which can be placed onto the view.\"" +
        "}" +
    " ]"
    
    
    // convert String to NSData
    let dataFromString: Data? = jsonString.data(using: String.Encoding.utf8)
    
    
    guard let data = dataFromString else {
        print("Error")
        return
    }
    
    do {
        let parsedData = try JSONSerialization.jsonObject(with: data, options: []) as! [[String:Any]]
    } catch let error {
        print(error)
    }
    

提交回复
热议问题