1

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 that will be creating JSON file and upload it to the server, I want to it looks like this
enter image description here

I will get all information from text fields and save it in JSON file like this(with oder values)

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

Is in swift any framework with function that can I use? Or I have to make it manually? If manually how can I save JSON file?

4

3 Answers 3

3

You can use JSONSerialization class for this purpose. Please see the code snippet below cooked up in Playground

import Foundation

// Dictionary containing data as provided in your question.
var dictonary : [String : Any] = ["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."
                                 ]


if let jsonData = try JSONSerialization.data(withJSONObject: dictonary, options: .init(rawValue: 0)) as? Data
{
    // Check if everything went well
    print(NSString(data: jsonData, encoding: 1)!)

    // Do something cool with the new JSON data
}

If you run this code in Xcode playground, you can see your data printed in JSON format Once you have the JSON , you can use the networking library of your choice to send the data over to the server.

Sign up to request clarification or add additional context in comments.

2 Comments

Please do to suggest to upload prettyprinted JSON to a server. The server doesn't care and the files contain a bunch of unnecessary whitespace and newline characters.
You can write just options: [] or completely omit , options: .init(rawValue: 0). No options is the default.
2

Swift 3/4

Save Json data in local file

func saveUploadedFilesSet(fileName:[String : Any]) {
        let file: FileHandle? = FileHandle(forWritingAtPath: "\(fileName).json")

        if file != nil {
            // Set the data we want to write
            do{
                if let jsonData = try JSONSerialization.data(withJSONObject: fileName, options: .init(rawValue: 0)) as? Data
                {
                    // Check if everything went well
                    print(NSString(data: jsonData, encoding: 1)!)
                    file?.write(jsonData)

                    // Do something cool with the new JSON data
                }
            }
            catch {

            }
            // Write it to the file

            // Close the file
            file?.closeFile()
        }
        else {
            print("Ooops! Something went wrong!")
        }
    }

Swift 3/4 Retrive json data from local file

func getUploadedFileSet(filename:String) {
    if let path = Bundle.main.path(forResource: "assets/\(filename)", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
            if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
                // do stuff
            }
        } catch let error {
            print("parse error: \(error.localizedDescription)")
        }
    } else {
        print("Invalid filename/path.")
    }
}

else you can convert [String:Any] Object to json

import Foundation

// Dictionary containing data as provided in your question.
var dictonary : [String : Any] = ["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."
                                 ]


if let jsonData = try JSONSerialization.data(withJSONObject: dictonary, options: .init(rawValue: 0)) as? Data
{
    // Check if everything went well
    print(NSString(data: jsonData, encoding: 1)!)

    // Do something cool with the new JSON data
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.