Objectmapper get array of one item within JSON

时间:2016-04-25 08:49:35

标签: arrays json swift realm 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[""]
    }
}

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?

1 个答案:

答案 0 :(得分:1)

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`.

So your code

typez <- map["types"]

doesn't work, since you assign values to the typez property directly.

The workaround is like the following:

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)
    }
    ...

First, store the mapped value to the local variable (it is string array). Then convert the string array to objects. Then append the objects to the List property.