【问题标题】:Writing JSON file programmatically swift以编程方式快速编写 JSON 文件
【发布时间】:2017-03-02 08:49:18
【问题描述】:

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

我将从文本字段中获取所有信息并将其保存在这样的 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 文件?

【问题讨论】:

标签: ios json swift


【解决方案1】:

您可以为此目的使用 JSONSerialization 类。请参阅下面在 Playground 中编写的代码 sn-p

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 Playground 中运行此代码,您可以看到以 JSON 格式打印的数据 获得 JSON 后,您可以使用您选择的网络库将数据发送到服务器。

【讨论】:

  • 请建议将 prettyprinted JSON 上传到服务器。服务器不在乎,文件包含一堆不必要的空格和换行符。
  • 您可以只写options: [] 或完全省略, options: .init(rawValue: 0)。没有选项是默认设置。
【解决方案2】:

斯威夫特 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!")
        }
    }

斯威夫特 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.")
    }
}

否则您可以将 [String:Any] 对象转换为 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
}

【讨论】:

    【解决方案3】:

    试试这个 Playground file

    斯威夫特 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 2015-02-11
      • 2016-07-27
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多