ios - 在 swift 中将数组转换为 JSON 字符串

标签 ios json string swift

如何在 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/

相关文章:

ios - 在 Phone Call 功能的 UIAlert 中添加取消功能

iphone - 如果设备上没有互联网连接,则 ios 应用程序会出错

ios - 在不剪切内容的情况下减小 UIView 的大小

java - settHeader ("content type"、 "") - 困惑

c - 如何比较字符数组和字符串

python - Python 如何从 argparse 填充字符串

python - 如何在python中输入一个大字符串?

iphone - 使用阻塞或类似方法从 NSURLConnection 获取数据

javascript - js删除提交的表单数据

json - 如何将嵌套的 JSON 转换为对象