SwiftyJSON 对象返回字符串

SwiftyJSON object back to string

我正在使用 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 都是 return 空值,但是当我尝试 eg println("content: "+libraryObject) 时,我在尝试将字符串附加到JSON

来自 SwiftyJSON 的 README on GitHub:

//convert the JSON to a raw String
if let string = libraryObject.rawString() {
//Do something you want
  print(string)
}
//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'
    }
}