如何使用ObjectMapper和Realm对象声明字典

时间:2017-01-10 05:54:28

标签: realm alamofire objectmapper

我使用ObjectMapper进行JSON解析,使用Realm进行持久化请帮助我如何声明字典以便它能够与Object Mapper和Realm一起使用。

 class UserInfo: Object,Mappable
{
var name:String?
var identifier:String?
var accountType:String?
var devices:[UserDevice]?
required init?(map: Map)
{

}

// Mappable
func mapping(map: Map)
{
    name <- map["username"]
    identifier <- map["identifier"]
    accountType <- map["accountType"]
    devices <- map["devices"]
}

}

==========

class UserDevice:Object,Mappable
{
var deviceName:String?
var deviceType:String?
var deviceIdentifier:String?

required init?(map: Map)
{

}

// Mappable
func mapping(map: Map) {
    deviceName <- map["name"]
    deviceType <- map["type"]
    deviceIdentifier <- map["identifier"]
}
}


 JSON :


 {
username = santhosh;
"identifier" = "IDJSDJSJS";
configstatus = SET;
configtype = DEFAULT;
"data_center" = "evs.idrive.com";
devices = {
    "Ankita\LKKKK" = {
        identifier = LJJDFDD;
        name = "Ankita iPAD";
        type = iPad;
    };
    "ARUN\LKKKHJH" = {
        identifier = LJJDFDFFD;
        name = "ARUN iPhone";
        type = ipHone;
    };

    accountStatus = 2;
    acctype = Test;
}

如何声明用户设备,使其与Realm和ObjectMapper兼容。

1 个答案:

答案 0 :(得分:0)

ObjectMapper extension for Realm允许您处理Realm List属性。

在上面的代码中,您没有像Realm认可的那样定义您的属性。您需要为所有基本类型添加dynamic前缀,并使用Realm List对象作为数组。

ObjectMapper扩展包含示例代码,用于说明如何解析List对象,但它看起来应如下所示:

class UserInfo: Object, Mappable
{
    dynamic var name: String?
    dynamic var identifier: String?
    dynamic var accountType: String?
    let devices = List<UserDevice>()

    func mapping(map: Map) {
        name       <- map["username"]
        identifier <- map["identifier"]
        accountType <- map["accountType"]
        devices    <- (map["devices"], ListTransform<User>())
    }
}

class UserDevice: Object, Mappable
{
    dynamic var deviceName: String?
    dynamic var deviceType: String?
    dynamic var deviceIdentifier: String?
}