我正在寻找一种在SWIFT中自动序列化和反序列化类实例的方法.让我们假设我们已经定义了以下类…

class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

…还有Person个例子:

let person = Person(firstName: "John", lastName: "Doe")

person的JSON表示如下所示:

{
    "firstName": "John",
    "lastName": "Doe"
}

Now, here are my questions:

  1. How can I serialize the person instance and get the above JSON without having to manually add all properties of the class to a dictionary which gets turned into JSON?
  2. 如何反序列化上面的JSON并返回一个静态类型为Person的实例化对象?同样,我不想手动映射属性.

以下是在C#中使用Json.NET时如何做到这一点:

var person = new Person("John", "Doe");
string json = JsonConvert.SerializeObject(person);
// {"firstName":"John","lastName":"Doe"}

Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);

推荐答案

WWDC2017@24:48(Swift 4)所示,我们将能够使用可编码协议.实例

public struct Person : Codable {
   public let firstName:String
   public let lastName:String
   public let location:Location
}

To serialize

let payload: Data = try JSONEncoder().encode(person)

To deserialize

let anotherPerson = try JSONDecoder().decode(Person.self, from: payload)

Note that all properties must conform to the Codable protocol.

An alternative can be JSONCodable which is used by Swagger's code generator.

Json相关问答推荐

我如何知道TJSONNumber是double还是double?

如何使用JQ将JSON字符串替换为解析后的类似功能?

使用JQ将对象数组转换为平面数组

将部分数据字节解组到自定义 struct 中

使用 Redis 作为键值存储

Bicep脚本中如何设置弹性池的维护窗口?

将JSON行转换为TSV格式, for each 数组项生成单独的行

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

使用杰克逊解析Kotlin 中的通用密封类

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

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

错误字符串的长度超过了maxJsonLength属性设置的值

如何使用 Serde 使用顶级数组反序列化 JSON?

什么是类型和类型令牌?

读取 HttpwebResponse json 响应,C#

如何在 json 编码字符串内的子数组数据周围添加方括号?

通过 JSON 发送 HTML 代码

Backbone.js 模型与集合

如何在本地存储中存储对象数组?

使用 JSON 迭代器输入安全警告