以编程方式快速写入JSON文件 [英] Writing JSON file programmatically swift

查看:152
本文介绍了以编程方式快速写入JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im制作测验应用程序,我想以JSON文件的形式从服务器下载问题,对其进行解析,然后制作将要呈现的问题对象.我这样做了,现在我想制作一个将创建JSON文件并将其上传到服务器的应用程序,我希望它看起来像这样

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

我将从文本字段中获取所有信息,并将其保存在这样的JSON文件中(带有奇异值)

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

是否迅速使用了可以使用的功能的框架? 还是我必须手动制作?如果手动,如何保存JSON文件?

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?

推荐答案

您可以为此目的使用JSONSerialization类.请查看下面在Playground中制作的代码段

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
}

如果您在Xcode操场上运行此代码,则可以看到以JSON格式打印的数据 有了JSON之后,您就可以使用所选的网络库将数据发送到服务器.

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.

这篇关于以编程方式快速写入JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆