简体   繁体   English

Realm + Swift,嵌套JSON

[英]Realm + Swift, nested JSON

I have a problem since last 2 days. 自从过去2天以来我遇到了问题。 I can't get my JSON transformed to a Realm Object. 我无法将我的JSON转换为Realm对象。

I have a json like below: 我有一个像下面这样的json:

{
  "gender" : "male",
  "id" : "123456789",
  "age_range" : {
    "min" : 21
  },
  "last_name" : "LastName" 
}

I have this Realm Models: 我有这个领域模型:

class UserObject: Object {

    dynamic var userId: String = ""
    dynamic var lastName: String?
    dynamic var gender: String?
    var ageRange = List<AgeRangeObject>()

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

class AgeRangeObject: Object {

    dynamic var min: Int = 0
}

And the way I am trying to create an instance of this model with ObjectMapper to parse json to dictionary and then create the model instance: 以及我尝试使用ObjectMapper创建此模型的实例以将json解析为字典然后创建模型实例的方式:

    let userJSONModel = Mapper<User>().map(jsonString)

    let realm = try! Realm()

    do {
        try realm.write {

            let dict: [String : AnyObject] = [
                "userId" : (userJSONModel?.userId)!,
                "ageRange" : (userJSONModel?.ageRange)!,
                "lastName" : (userJSONModel?.lastName)!,
                "gender" : (userJSONModel?.gender)!
            ]

            let userModel = UserObject(value: dict)

            realm.add(userModel)
        }
    } catch {
        print("Exception")
    }

The problem occurs on this line: let userModel = UserObject(value: dict) 问题出现在这一行: let userModel = UserObject(value: dict)

I get the folowing error: 我得到了以下错误:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Invalid value 'min' to initialize object of type 'AgeRangeObject': missing key 'min''

I was looking on the stackoverflow: 我正在查看stackoverflow:

Nested Arrays throwing error in realm.create(value: JSON) for Swift 嵌套数组在Swift的realm.create(value:JSON)中抛出错误

How to convert Realm object to JSON with nested NSDate properties? 如何使用嵌套的NSDate属性将Realm对象转换为JSON?

but my case is different. 但我的情况有所不同。 Do you know what's the problem with that age range dictionary? 你知道那个年龄段字典有什么问题吗? Why it can't parse it well? 为什么它不能很好地解析它? Thank you. 谢谢。

In your JSON, ageRange is a dictionary, whereas the UserObject.ageRange property is a List<AgeRangeObject> . 在您的JSON中, ageRange是一个字典,而UserObject.ageRange属性是List<AgeRangeObject> You have mismatched models. 你有不匹配的模型。

You either need to update your models to reflect the structure of your JSON: 您需要更新模型以反映JSON的结构:

var ageRange = List<AgeRangeObject>()

becomes

dynamic var ageRange: AgeRangeObject? = nil

or vice versa, update your JSON to reflect the structure of your models: 反之亦然,更新您的JSON以反映模型的结构:

{
  "gender" : "male",
  "id" : "123456789",
  "age_range" : [{
    "min" : 21
  }],
  "last_name" : "LastName" 
}
{
  "key1" : "value1",
  "key2" : "value2",
  "array1" : [{
    "key" : value
  }],
 "key3" : "value3" 
}

For this you could use ObjectMapper's TransformType. 为此,您可以使用ObjectMapper的TransformType。

Reference: https://github.com/APUtils/ObjectMapperAdditions 参考: https//github.com/APUtils/ObjectMapperAdditions

My Code: 我的代码:

@objcMembers class RealmObject: Object, Mappable {

  dynamic var listValues = List<MyRealmObject>()

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

 // Mappable
 func mapping(map: Map) {
   listValues <- (map["listValues"], RealmlistObjectTransform())
  }

}

@objcMembers class MyRealmObject: Object, Mappable {

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

    // Mappable
    func mapping(map: Map) {

    }
  }

class RealmlistObjectTransform: TransformType {
    typealias Object = List<MyRealmObject> // My Realm Object here
    typealias JSON = [[String: Any]] // Dictionary here

    func transformFromJSON(_ value: Any?) -> List<MyRealmObject>? {
      let list = List<MyRealmObject>()
      if let actors = value as? [[String: Any]]  {
        let objects = Array<MyRealmObject>(JSONArray: actors)
        list.append(objectsIn: objects)
      }
      return list
    }

    func transformToJSON(_ value: List<MyRealmObject>?) -> [[String: Any]]? {
      if let actors = value?.sorted(byKeyPath: "").toArray(ofType: MyRealmObject.self).toJSON() {
        return actors
      }
      return nil
    }
  }

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

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