json - 使用 ObjectMapper 从 JSON 反序列化为自定义对象

标签 json swift objectmapper

我在使用 ObjectMapper 将 JSON 数据反序列化为自定义对象时遇到问题。

结构是这样的:

{
  "message": "",
  "payload": [
    {
      "details": {
        "id": "7758931",
        "description": "A description",
...

我的代码:

struct MyObject : Mappable
    {
        var message : String
        var payload : [MyDetail]?

        init(map: Mapper) throws
        {
            try message = map.from("message")
            payload = map.optionalFrom("payload") ?? nil
        }
    }

struct MyDetail : Mappable
{
    var detailId : String
    var descriptionDetail : String

    init(map: Mapper) throws
    {
        try detailId = map.from("id")
        try descriptionDetail = map.from("description")
    }
}

显然这是不正确的,因为有一个包含要解析的关键细节的字典......

有人知道我该如何解析吗?

最佳答案

您需要一个包装详细信息的容器对象,因为它嵌套在 details 键下,如下所示:

struct MyObject : Mappable {
    var message : String
    var payload : [MyDetailContainer]?

    init(map: Mapper) throws {
        try message = map.from("message")
        payload = map.optionalFrom("payload") ?? nil
    }
}

struct MyDetailContainer : Mappable {
    var details: MyDetail

    init(map: Mapper) throws {
        try details = map.from("details")
    }
}

struct MyDetail : Mappable {
    var detailId : String
    var descriptionDetail : String

    init(map: Mapper) throws
    {
        try detailId = map.from("id")
        try descriptionDetail = map.from("description")
    }
}

假设json是这样继续下去的:

{
  "message": "",
  "payload": [
    {
      "details": {
        "id": "7758931",
        "description": "A description"
      },
    },
    {
      "details": {
        "id": "7758932",
        "description": "Description #2"
...

关于json - 使用 ObjectMapper 从 JSON 反序列化为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38737465/

相关文章:

java - JSONObject ["name"] 不是字符串

ios - UITableView 不显示滚动

ios - Twitter/Fabric 登录按钮只能工作一次

php - 通过表单更新 JSON?

jQuery JSON 编码输入值集

javascript - 在 Angularjs 中将 Javascript 对象转换为 JSON 一次

swift - Swift 中的 adMob 智能横幅

swift - 带 OR 运算符的 Realm 主键

swift - 如何通过 objectMapper 和 Alamofire 发布嵌套的 json?

json - 如何使用对象映射器从 Realm "Results"创建 JSON 格式