2017-03-02 86 views
-1

即时通讯制作测验应用程序,我想从JSON文件中的服务器下载问题,解析它并制作问题对象,我将介绍它。我做到了,所以现在我想做出将创建JSON文件,并将其上传到服务器上的应用程序,我想它看起来像这样
enter image description here以编程方式快速编写JSON文件

我会从文本字段中的所有信息,并将其保存在这样的JSON文件(与奥德值)

[ 
{ 
    "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文件?

+0

'JSONSerialization'数据! – luk2302

+0

你应该看看SwiftyJSON(https://github.com/SwiftyJSON/SwiftyJSON) – mlidal

+0

我认为这可能会帮助你:[http://stackoverflow.com/questions/28768015/how-to-save-an-array- as-a-json-file-in-swift](http://stackoverflow.com/questions/28768015/how-to-save-an-array-as-a-json-file-in-swift) – chengsam

回答

3

您可以使用JSONSerialization类来达到此目的。请参阅下面的代码片段炮制的游乐场

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,你可以使用的网络库您选择将数据发送到服务器。

+0

请建议将* prettyprinted * JSON上传到服务器。服务器不关心,文件包含一堆不必要的空白和换行符。 – vadian

+2

你可以只写'options:[]'或完全省略',options:.init(rawValue:0)'。没有选项是默认值。 – vadian

1

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

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