SwiftyJSON对象回到字符串

问题描述 投票:27回答:2

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

ios json swift swifty-json
2个回答
72
投票

来自SwiftyJSON on GitHub的自述文件:

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

5
投票

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'
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.