1

yeah, it's a solution, but not perfect for following case.

JSON from server
{
    id: "4",
    key: "web_banner",
    data: [
        {
            id: "11",
            title: "app",
            description: "",
        }
    ]
}

i use ObjectMapper for mapping, so as the JSON schema, i create the following models

class Advertising: Object, Mappable {

    dynamic var id               = ""
    dynamic var key            = ""
    private var   data         = [AdvertisingData]()
    {
        willSet{// **i have to do this for Store it, it will be empty in realm if not do this**
            dataList.removeAll()
            dataList.appendContentsOf(newValue)
        }
    }
    let dataList = List<AdvertisingData>()

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

    func mapping(map: Map) {
        id <- map["id"]
    key <- map["advertising_key"]
    data <- map["advertising_data"]
    }

    override class func ignoredProperties() -> [String] {
        return ["data"]
    }

}

class AdvertisingData: Object, Mappable {

    dynamic var id             = ""
    dynamic var title          = ""
    dynamic var theDescription = “”

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

    func mapping(map: Map) {
        id <-             map["id"]
        title <-          map["title"]
        theDescription <- map["description"]
    }

}
  1. i must declare the data in class Advertising just for sync data to dataList,
  2. i have to ignore the property data this is my solution, too ugly, some good idea? Thank you in advance
Dmitry
  • 7,300
  • 6
  • 32
  • 55
巩小鹏
  • 69
  • 1
  • 6

1 Answers1

3

From Realm docs:

If your JSON schema doesn’t align exactly with your Realm objects, we recommend you use a third party model mapping framework in order to transform your JSON. Swift has a thriving set of actively maintained model mapping frameworks which work with Realm, some of which are listed in the realm-cocoa repository.

So just use one of this frameworks for mapping.

Dmitry
  • 7,300
  • 6
  • 32
  • 55
  • It's a solution, but not perfect for the case. i have changed my question to show the case – 巩小鹏 Jun 16 '16 at 11:32
  • @巩小鹏 as the initial question was changed, I suggest you to look at this question: http://stackoverflow.com/questions/33804181/alamofire-objectmapper-realm-nested-objects – Dmitry Jun 16 '16 at 12:14
  • Thanks, i have found the best solution for me! – 巩小鹏 Jun 16 '16 at 13:40