ios SwiftyJSON 对象返回字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31142091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SwiftyJSON object back to string
提问by Derek
I'm using the SwiftyJSON library to parse JSON into swift objects. I can create the JSON object and read and write to it
我正在使用 SwiftyJSON 库将 JSON 解析为 swift 对象。我可以创建 JSON 对象并对其进行读写
// Create json object to represent library
var libraryObject = JSON(["name":"mylibrary","tasks":["Task1","Task2","Task3"]])
// Get
println(libraryObject["name"])
println(libraryObject["tasks"][0])
// Set
println("Setting first task to 'New Task'")
libraryObject["tasks"][0] = "New Task"
// Get
println(libraryObject["tasks"][0])
// Convert object to JSON and print
println(libraryObject)
All of this works as expected. I just want to convert the libraryObject back to a string in JSON format!
所有这些都按预期工作。我只想将 libraryObject 转换回 JSON 格式的字符串!
The println(libraryObject) command outputs what I want to the console but I can't find a way to get it as a string.
println(libraryObject) 命令将我想要的内容输出到控制台,但我找不到将其作为字符串获取的方法。
libraryObject.Stringvalue and libraryObject.String both return empty values but when I try eg println("content: "+libraryObject) I get an error trying to append a String to a JSON
libraryObject.Stringvalue 和 libraryObject.String 都返回空值,但是当我尝试使用 println("content: "+libraryObject) 时,尝试将字符串附加到 JSON 时出错
回答by Raja Vikram
回答by Mehdico
//convert the JSON to a raw String
if let strJson = jsonObject.rawString() {
// 'strJson' contains string version of 'jsonObject'
}
//convert the String back to JSON (used this way when used with Alamofire to prevent errors like Task .<1> HTTP load failed (error code: -1009 [1:50])
if let data = strJson.data(using: .utf8) {
if let jsonObject = try? JSON(data: data) {
// 'jsonObject' contains Json version of 'strJson'
}
}