matthewcheok / Realm-JSON

A concise Mantle-like way of working with Realm and JSON.
MIT License
661 stars 129 forks source link

How to map object coming in array and not a dictionary? #88

Closed Voley closed 8 years ago

Voley commented 8 years ago

I'm getting an array of objects, like so:

Image of data

I have created a DayObject, how do I write JSONInboundMappingDictionary for it?

Since the data is in arrays and not dictionary.

Regards

viktorasl commented 8 years ago

Hey. Is the DayObject class an entry of day_choices array? If so, you should be able to define JSONInboundMappingDictionary class method for DayObject. Of course JSON response should be received like an object of some class DayOptions which will look like:

class DayOptions: RLMObject {
    dynamic var day_choices = RLMArray(objectClassName: DayObject.className())
    static var JSONInboundMappingDictionary: NSDictionary = [
        "day_choices": "day_choices"
    ]
}

As I remember day_choices mapping will trigger JSONInboundMappingDictionary for each DayObject array entry.

Voley commented 8 years ago

@viktorasl

Yes I do have parent object that has an array of DayChoice objects. It parses fine, but I don't know how to make DayChoices map. Day Object has a number and string properties, how will it know where to map what with your mapping?

viktorasl commented 8 years ago

Oh, ok, so as I understand now day_choices is an array of array of two values: string and int? If so it's pretty much against "array" definition (not taking into account Javascript and similar not so strict languages). Array is a collection of the same type values. So you have two options:

  1. Read them all as strings and then take into account that first is a number (if you're not able to change the API)
  2. I have made a pull request allowing modification of JSON before saving to the DB (https://github.com/matthewcheok/Realm-JSON/pull/86) so you would be able to modify your JSON
  3. Fork a repo and extend mapping which will allow mapping properties with array elements
matthewcheok commented 8 years ago

@viktorasl is right - I've merged #86 so that might work.