这比班级还低

class User: NSManagedObject {
  @NSManaged var id: Int
  @NSManaged var name: String
}

需要转换为

{
    "id" : 98,
    "name" : "Jon Doe"
}

I tried manually passing the object to a function which sets the variables into a dictionary and returns the dictionary. But I would want a better way to accomplish this.

推荐答案

在SWIFT 4中,您可以继承Codable类型.

struct Dog: Codable {
    var name: String
    var owner: String
}

// Encode
let dog = Dog(name: "Rex", owner: "Etgar")

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(dog)
let json = String(data: jsonData, encoding: String.Encoding.utf16)

// Decode
let jsonDecoder = JSONDecoder()
let secondDog = try jsonDecoder.decode(Dog.self, from: jsonData)

Json相关问答推荐

Jolt Change将对象添加到数组

JOLT转换过滤出特定值/对象

处理输入数据并转换为更简单的格式-PowerBI

解析Ansible AWS ec2_security_group中的json以提取安全组ID

使用 jq 重新格式化 JSON 输出

jq - 仅在键值对存在的地方打印值

使用jq根据对象中键的值查找对象

如何使用 SQL Server 将 json 存储为字符串的列分解/规范化为行和列?

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

嵌套存储在字符串变量中的 JSON 对象

无法在 json --data 中使用变量

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

如何从 JSON 中获取数据并通过 vb6 在网格中显示

如何在 Node.js 中解析包含NaN的 JSON 字符串

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

如何使用 Kotlin + Jackson 将 JSON 反序列化为 List

如何使用 json.net 将数据表转换为 json 字符串?

将带有数据和文件的 JSON 发布到 Web Api - jQuery / MVC

Django - 异常处理最佳实践和发送自定义错误消息

什么 Python 框架用于没有前端的 REST/JSON Web 服务?