2017-03-02 78 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.") 
    } 
}