在swift中将数组转换为JSON字符串
如何在swift中将数组转换为 JSON 字符串?
基本上我有一个嵌入按钮的文本字段。
按下按钮时,文本字段文本被添加到 testArray
。
此外,我想将此数组转换为 JSON 字符串。
How do you convert an array to a JSON string in swift?
Basically I have a textfield with a button embedded in it.
When button is pressed, the textfield text is added unto the testArray
.
Furthermore, I want to convert this array to a JSON string.
这是我尝试过的:
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 字符串。
I would also like to return the JSON string using my savetoDictionart()
method.
因为它正在将它转换为数据,然后尝试将数据转换为对象作为JSON(失败,它不是JSON)并将其转换为字符串,基本上你有一堆无意义的转换。
As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.
只要数组只包含JSON可编码值(字符串,数字,字典, array,nil)你可以使用NSJSONSerialization来完成它。
As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.
而只是做数组 - >数据 - >字符串部分:
Instead just do the array->data->string parts:
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)
虽然您可能不应该使用强制解包,但它会为您提供正确的起点。
although you should probably not use forced unwrapping, it gives you the right starting point.