如何将字典转换为没有空格和新行的json字符串

Pak*_*ung 4 json dictionary swift

我试图将字典转换为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}]}]}"
Run Code Online (Sandbox Code Playgroud)

我的转换

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)
Run Code Online (Sandbox Code Playgroud)

结果

{
    requests =     (
                {
            features =             (
                                {
                    type = "LABEL_DETECTION";
                },
                                {
                    type = "WEB_DETECTION";
                },
                                {
                    type = "TEXT_DETECTION";
                }
            );
            image =             {
                content = "iVBO
      ...........
Run Code Online (Sandbox Code Playgroud)

Cal*_*lam 11

您正在将序列化的JSON解码为对象.将对象打印到控制台时,您将看到缩进,并使用等号和括号.

删除该.prettyPrinted选项并使用数据初始化带.utf8编码的字符串.

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