如何在 swift 中将数组转换为 JSON 字符串?
基本上我有一个文本字段,其中嵌入了一个按钮。
按下按钮时,文本字段文本将添加到 testArray
中。
此外,我想将此数组转换为 JSON 字符串。
这是我尝试过的:
func addButtonPressed() {
if goalsTextField.text == "" {
// Do nothing
} else {
testArray.append(goalsTextField.text)
goalsTableView.reloadData()
saveDatatoDictionary()
}
}
func saveDatatoDictionary() {
data = NSKeyedArchiver.archivedDataWithRootObject(testArray)
newData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(), error: nil) as? NSData
string = NSString(data: newData!, encoding: NSUTF8StringEncoding)
println(string)
}
我还想使用我的 savetoDictionart()
方法返回 JSON 字符串。
最佳答案
就目前情况而言,您将其转换为数据,然后尝试将数据转换为 JSON 形式的对象(失败,它不是 JSON)并将其转换为字符串,基本上您会进行一堆无意义的转换。
只要数组仅包含 JSON 可编码值(字符串、数字、字典、数组、nil),您就可以使用 NSJSONSerialization 来完成此操作。
只需执行数组->数据->字符串部分即可:
swift 3/4
let array = [ "one", "two" ]
func json(from object:Any) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
print("\(json(from:array as Any))")
原始答案
let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
虽然您可能不应该使用强制展开,但它为您提供了正确的起点。
关于ios - 在 swift 中将数组转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42027137/