我使用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)
所有这些都按预期工作。我只想将libraryObject转换回JSON格式的字符串!
println(libraryObject)命令将我想要的内容输出到控制台但我无法找到将其作为字符串获取的方法。
libraryObject.Stringvalue和libraryObject.String都返回空值但是当我尝试例如println(" content:" + libraryObject)时,我尝试将字符串附加到JSON时出错
答案 0 :(得分:68)
来自SwiftyJSON的自述文件on GitHub:
//convert the JSON to a raw String
if let string = libraryObject.rawString() {
//Do something you want
print(string)
}
答案 1 :(得分:2)
Swift 4.2版本
//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'
}
}