简体   繁体   中英

Parse JSON and save with Realm

I have this JSON data:

{
  "id": 120,
  "userId": 1,
  "key": [
    56,
    21,
    133,
    77
  ]
}

I use JSONHelper to parse it, and save it locally with Realm .

The problem is that I can't save the Int array locally and if I try to change the object to a simple object in Swift, the parser doesn't work.

Models

class Response: RLMObject, Deserializable {
    dynamic var _id = 0
    dynamic var userId = 0
    var key = List<HashInt>()

    required init(data: JSONDictionary) {
        super.init()
        _id            <-- (data["id"])
        userId         <-- data["userId"]
        key            <-- data["key"]
    }

    override init() {
        super.init()
    }
}

class HashInt: Object, Deserializable {

    dynamic var value = ""

    required init(data: JSONDictionary) {
        super.init()
        value <-- data["value"]
    }

    required init() {
        super.init()
    }
}

I need to parse the Int array and save it locally with Realm. How can I achieve that?

First of all, you'll need to decide between Realm Swift and Realm Objective-C. You can't mix both. Either you let your objects inherit from Object or RLMObject . In my answer I'll assume, you want to go full Swift.

You can't map via JSONHelper, because it doesn't have a concept of constructing Realm Swift's List type. But you can map to a Swift array.

var keyObjects = [HashInt]()
keyObjects <-- data["key"]
for keyObject in keyObjects {
     key.append(keyObject)
}

If you have more than one to-many relationship, it would make sense to look into overloading JSONHelper's mapping operator ( <-- ), so that it supports mapping to Realm Swift's List type. This might look like below. (untested!)

import RealmSwift

public func <-- <T: Deserializable>(list: List<T>, dataObject: AnyObject?) {
    var newArray = [T]()
    newArray <-- dataObject
    for object in newArray {
       list.append(object)
    }
    return list
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM