以编程方式快速编写 JSON 文件
Posted
技术标签:
【中文标题】以编程方式快速编写 JSON 文件【英文标题】:Writing JSON file programmatically swift 【发布时间】: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 文件?
【问题讨论】:
JSONSerialization
!
你应该看看 SwiftyJSON (github.com/SwiftyJSON/SwiftyJSON)
我想这可能对你有帮助:http://***.com/questions/28768015/how-to-save-an-array-as-a-json-file-in-swift
alamofire 框架是最好的选择:)
【参考方案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)
【讨论】:
以上是关于以编程方式快速编写 JSON 文件的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式为 BigQuery 服务传递服务帐户凭据(JSON 文件)