I'm trying to serialize my object as following:

import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

let user = User(username: "John", profileURL: "http://google.com")

let json = try? JSONEncoder().encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}

However on macOS I'm getting the following:

{"profileURL":"http:\/\/google.com","username":"John"}

(note escaped '/' character).

在Linux机器上,我得到以下信息:

{"username":"John","profileURL":"http://google.com"}

如何让JSONEncoding返回未转义的?

I need the string in JSON to be strictly unescaped.

推荐答案

For iOS 13+ / macOS 10.15+

let user = User(username: "John", profileURL: "http://google.com")

let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .withoutEscapingSlashes
let json = try? jsonEncoder.encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}

Console O/P

{"profileURL":"http://google.com","username":"John"}


注释\/中的Martin R提到的NOTE:是有效的JSON转义序列.

Json相关问答推荐

按照对象键的值对PostgreSQL JSONB对象进行排序'

与错误相关的未定义&Quot;不是有效的JSON

如何用JQ更改空/布尔/数字的 colored颜色 ?

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

如何在Swift中使用JSON编码器的泛型

使用快速json库编写json可以消除所有缩进

基于 JSON 字段的 Jolt 条件标志

Jolt Spec 跳过数组中的第一个元素

震动范围改善

如何在 terraform 输出中打印一组用户信息

如何使用 jq 将字符串数组转换为对象?

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

使用 jq 获取特定键的所有父键

使用 Jolt 使用键中的值创建带有硬编码键和值的 JSON 数组

Python Flask-Restful POST 不采用 JSON 参数

Json.Net:用于自定义命名的 JsonSerializer-Attribute

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性

春天:返回@ResponseBodyResponseEntity>