简体   繁体   English

解析JSON并使用Realm保存

[英]Parse JSON and save with Realm

I have this JSON data: 我有以下JSON数据:

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

I use JSONHelper to parse it, and save it locally with Realm . 我使用JSONHelper进行解析,并使用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. 问题是我无法在本地保存Int数组,并且如果我尝试在Swift中将对象更改为简单对象,则解析器将无法正常工作。

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. 我需要解析Int数组,并使用Realm将其保存在本地。 How can I achieve that? 我该如何实现?

First of all, you'll need to decide between Realm Swift and Realm Objective-C. 首先,您需要在Realm Swift和Realm Objective-C之间做出选择。 You can't mix both. 不能混用。 Either you let your objects inherit from Object or RLMObject . 您可以让对象继承自ObjectRLMObject In my answer I'll assume, you want to go full Swift. 在我的回答中,我假设您想全面学习Swift。

You can't map via JSONHelper, because it doesn't have a concept of constructing Realm Swift's List type. 您无法通过JSONHelper进行映射,因为它没有构造Realm Swift的List类型的概念。 But you can map to a Swift array. 但是您可以映射到Swift数组。

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. 如果您有多个关系,则可以考虑重载JSONHelper的映射运算符( <-- ),以便它支持映射到Realm Swift的List类型。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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