Objectmapper内JSON获得一个项目的数组 [英] Objectmapper get array of one item within JSON

查看:1584
本文介绍了Objectmapper内JSON获得一个项目的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下的JSON,其中我与ObjectMapper和境界一起使用。

So I have the following JSON, which I am using together with ObjectMapper and Realm.

{
  "result": [
    {
      "id": 20,
      "types": [
        "now"
      ],
      "url": "/nl/whereto/ezrhgerigerg",
      "categories": [
        {
          "id": 39,
          "name": "Food "
        },
        {
          "id": 21,
          "name": "Varia"
        }
      ]
    },

我的问题越来越从类型,这对于在阵列中的某些项目说现在或晚的数据,并且是空的其他项目(因此,没有类型项被给定)。

My problem is getting the data from "types", which for some items in the array says "now" or "later", and is empty for other items (hence, no types item is given).

我试图做我的映射如下:

I tried to do the following in my mapping:

class Publication: Object, Mappable {
    dynamic var id:Int = 0
    var typez  = List<getType>()
    dynamic var url:String?

    required convenience init?(_ map: Map) {
        self.init()
    }

    override static func primaryKey() -> String? {
        return "id"
    }

    func mapping(map: Map) {
        id <- map["id"]
        typez <- map["types"]
        url <- map["url"]
    }
}

class getType: Object, Mappable {
    dynamic var text: String = ""


    required convenience init?(_ map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        text <- map[""]
    }
}

当我检查域数据库,可以看到typez的[的getType]数组被做了,但它是空的所有项目(即使的那些类型的地方就是现在)。其他两个项目(ID和URL)在数据库填充

When I check the Realm database, you can see that typez, an array of [getType] was made, but it's empty for all items (even the ones where types is "now"). The other two items (id and url) are filled in in the database.

我在做什么错,它不会保存到数据库?

What am I doing wrong that it won't save to the database?

推荐答案

由于境界无法检测,因为列表指定列表属性属性不Objective-C的类型。因此,列表属性应该被声明为,而不应。您应该使用追加 /删除... / 插入... 法修改 List`。

Because Realm cannot detect assigning List properties since List property is not Objective-C type. So List properties should be declared as let, and should not be nil. You should use append/remove.../insert...method to modifying theList`.

所以你的code

typez <- map["types"]

不起作用,因为你赋值给 typez 属性直接。

解决方法是这样的:

func mapping(map: Map) {
    ...
    var typez: [String]? = nil
    typez <- map["types"]

    typez?.forEach { t in
        let obj = getType()
        obj.text = t
        self.typez.append(obj)
    }
    ...

首先,存储映射值局部变量(这是字符串数组)。然后,字符串数组转换为对象。然后追加对象到列表属性。

这篇关于Objectmapper内JSON获得一个项目的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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