【问题标题】:What is the easiest way to create readable JSON string?创建可读 JSON 字符串的最简单方法是什么?
【发布时间】:2018-01-16 12:15:51
【问题描述】:

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

但是下面的代码产生的字符串只要一行行。

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

有没有创建多行 JSON 字符串的默认方法?

【问题讨论】:

标签: ios json swift swift4


【解决方案1】:

您可以使用JSONSerializationprettyPrinted 选项

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
}

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2011-03-25
    • 2014-01-28
    • 1970-01-01
    • 2014-07-01
    • 2011-08-22
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多