创建可读JSON字符串的最简单方法是什么?

时间:2018-01-16 12:15:52

标签: ios json swift swift4

我想用新行和制表符(或空格)绘制格式化的JSON字符串。

但下面的代码会产生一个字符串长的文字。

let resultString = String(data: response.data, encoding: .utf8)

是否有任何默认方法来创建多行JSON字符串?

1 个答案:

答案 0 :(得分:1)

您可以使用prettyPrinted

JSONSerialization选项
do {
    let json = try JSONSerialization.jsonObject(with: response.data, options: []) as! [String: AnyObject]
    let formattedJson = try JSONSerialization.data(withJSONObject: json, options:JSONSerialization.WritingOptions.prettyPrinted )
    if let formattedString = String(data: formattedJson, encoding: .utf8) {
        print(formattedString)
    }
} catch {
    print("Error: \(error)")
}

对于Swift 4中引入的JSONEncoder,有一个prettyPrinted选项:

struct Foo: Codable {
    var bar: String
    var baz: Int
}

let foo = Foo(bar: "gfdfs", baz: 334)

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // This makes it formatted as multiline

let data = try encoder.encode(foo)
print(String(data: data, encoding: .utf8)!)

输出结果为:

{
  "bar" : "gfdfs",
  "baz" : 334
}