簡體   English   中英

以編程方式快速編寫 JSON 文件

[英]Writing JSON file programmatically swift

我正在制作測驗應用程序,我想從 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 文件?

為此,您可以使用 JSONSerialization 類。 請參閱下面在 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 playground 中運行此代碼,您可以看到以 JSON 格式打印的數據 一旦您擁有 JSON ,您就可以使用您選擇的網絡庫將數據發送到服務器。

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

否則你可以將 [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
}

試試這個Playground 文件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM