如何将Swift对象序列化或转换为JSON? [英] How to serialize or convert Swift objects to JSON?

查看:651
本文介绍了如何将Swift对象序列化或转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该类下级

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类型.

In Swift 4, you can inherit from the Codable type.

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 dog = try jsonDecoder.decode(Dog.self, from: jsonData)

这篇关于如何将Swift对象序列化或转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆