【问题标题】:How to convert dictionary to json string without space and new line如何将字典转换为没有空格和换行的json字符串
【发布时间】:2018-04-20 14:25:20
【问题描述】:

我正在尝试将字典转换为没有空格和换行符的 json 字符串。我尝试使用 JSONSerialization.jsonObject 但我仍然可以看到空格和换行符。有没有办法让字符串结果看起来像这样

"data": "{\"requests\":[{\"image\":{\"source\":{\"imageUri\":\"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png\"}},\"features\":[{\"type\":\"LOGO_DETECTION\",\"maxResults\":1}]}]}"

我的转化

var features = [[String: String]]()
for detection in detections {
    features.append(["type": imageDetection[detection]!])
}
let content = ["content": base64Image]
let request = ["image": content, "features": features] as [String : Any]
let requests = ["requests": [request]]

let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: .prettyPrinted)
let decoded = try! JSONSerialization.jsonObject(with: jsonData, options: [])
print(decoded)

结果

{
    requests =     (
                {
            features =             (
                                {
                    type = "LABEL_DETECTION";
                },
                                {
                    type = "WEB_DETECTION";
                },
                                {
                    type = "TEXT_DETECTION";
                }
            );
            image =             {
                content = "iVBO
      ...........

【问题讨论】:

  • .prettyPrinted 是罪魁祸首
  • 删除选项也得到相同的结果

标签: json swift dictionary


【解决方案1】:

您正在将序列化的 JSON 解码为一个对象。当一个对象被打印到控制台时,你会看到缩进,以及等号和括号的使用。

去掉.prettyPrinted选项,使用数据初始化一个带有.utf8编码的字符串。

let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: [])
let decoded = String(data: jsonData!, encoding: .utf8)!

【讨论】:

    猜你喜欢
    • 2016-12-06
    • 2016-05-25
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多