通过稍微修改您的 JSON,无论是在源代码中还是作为代码中映射步骤的一部分,您都可以将其直接传递给 Realm 的 KVC 初始化机制:
{
"name": "Product 1",
"features": [
[[
{ "locale": "en", "value": "feature1" },
{ "locale": "cn", "value": "feature1 in cn" }
]],
[[
{ "locale": "en", "value": "feature2" },
{ "locale": "cn", "value": "feature2 in cn" }
]]
]
}
映射到这些领域模型:
@interface Feature : RLMObject
@property NSString *locale;
@property NSString *value;
@end
@implementation Feature
@end
RLM_ARRAY_TYPE(Feature);
@interface FeatureList : RLMObject
@property RLMArray<Feature> *features;
@end
@implementation FeatureList
@end
RLM_ARRAY_TYPE(FeatureList);
@interface Product : RLMObject
@property NSString *name;
@property RLMArray<FeatureList> *features;
@end
@implementation Product
@end
此时,您可以将 JSON 反序列化为字典并使用以下命令初始化您的 Realm 对象图:
NSDictionary *productDictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"product" withExtension:@"json"]] options:0 error:nil];
[Product createInDefaultRealmWithValue:productDictionary];
它为您提供以下对象图:
[0] Product {
name = Product 1;
features = RLMArray <0x7fe43366be00> (
[0] FeatureList {
features = RLMArray <0x7fec3a772c10> (
[0] Feature {
locale = en;
value = feature1;
},
[1] Feature {
locale = cn;
value = feature1 in cn;
}
);
},
[1] FeatureList {
features = RLMArray <0x7fec3a773d20> (
[0] Feature {
locale = en;
value = feature2;
},
[1] Feature {
locale = cn;
value = feature2 in cn;
}
);
}
);
}