json - 如何将字典转换为不带空格和换行符的json字符串

标签 json swift dictionary

我正在尝试将字典转换为不带空格和换行符的 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
      ...........

最佳答案

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

移除.prettyPrinted选项,使用数据初始化一个.utf8编码的字符串。

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

关于json - 如何将字典转换为不带空格和换行符的json字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47170571/

相关文章:

iphone - UITableViewCell 中的 MKMapView

javascript - Google Recaptcha - GetResponse 不返回 JSON

java - 我的 Java Web 服务返回一个包裹在 html 中的 JSON 字符串,我如何删除 HTML

arrays - 尝试使用 contains() 将字符串与数组内对象内找到的字符串进行比较

swift - 用于在 Xcode 中实现自定义 UI 设计的资源

ios - 使用 CoreData 保存包含字典的数组

java - map 不接受子类

python - 将具有日期时间值的字典的字符串表示形式转换回字典

javascript - 重新排列数组中每个元素的顺序

javascript - 使用 javascript 将对象合并到 json 中