将SwiftyJSON对象转换为字符串

40

我正在使用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时出错。

2个回答

86

以下内容摘自 SwiftyJSON 的 GitHub README

//convert the JSON to a raw String
if let string = libraryObject.rawString() {
//Do something you want
  print(string)
}

3
我发誓我尽力了,但是就是完全忘记了!非常感谢。 - Derek
3
请确保使用.rawString()而不是.rawString(没有括号)。花了很长时间才弄清楚为什么我没有得到相同的结果。 - Nathan

6
//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'
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接