我使用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兼容。
答案 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?
}