以编程方式快速编写JSON文件

时间:2017-03-02 08:49:18

标签: ios json swift

我正在制作测验应用程序,我想从JSON文件中的服务器下载问题,解析它并制作我将提出的问题对象。我这样做了所以现在我想创建一个将创建JSON文件并将其上传到服务器的应用程序,我希望它看起来像这样 enter image description here

我将从文本字段中获取所有信息并将其保存在JSON文件中(使用oder值)

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

在swift任何具有我可以使用的功能的框架中吗? 或者我必须手动制作?如果手动如何保存JSON文件?

3 个答案:

答案 0 :(得分:3)

您可以使用JSONSerialization类来实现此目的。请参阅下面在Playground中编写的代码片段

var xml = XDocument.Load("D:\\temp.xml");

如果您在Xcode playground中运行此代码,您可以看到以JSON格式打印的数据 获得JSON后,您可以使用您选择的网络库将数据发送到服务器。

答案 1 :(得分:1)

试试这个 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)
}

答案 2 :(得分:1)

Swift 3/4

将Json数据保存在本地文件中

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 从本地文件中回复json数据

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