我试图从JSON文件(使用swiftyJSON)写入一个Realm DB得到以下错误:
我的JSON文件结构如下:libc + + abi。dylib:以未捕获的NSException类型异常结束***由于未捕获异常'RLMException'而终止应用程序,原因:'无效值'{"vehicle":真的,"viewable":真的,"id": 0,"weapon":假的,"genres": "[幻想,一般]","name":";Car"}'初始化'Item'类型的对象:缺少键'id "
[
{
"id": 0,
"name": "Car",
"genres": "[Fantasy, General]",
"viewable": true,
"weapon": false,
"vehicle": true
},
{
"id": 1,
"name": "Truck",
"genres": "[General]",
"viewable": true,
"weapon": false,
"vehicle": true
},
]
My Realm DB Class is:
class Item: Object {
@objc dynamic var id: Int = 0
@objc dynamic var name = ""
let genres = List<String>()
@objc dynamic var visable: Bool = false
@objc dynamic var weapon: Bool = false
@objc dynamic var vehicle: Bool = false
override static func primaryKey() -> String? {
return "id"
}
override static func indexedProperties() -> [String] {
return ["genre", "visable"]
}
}
,将JSON写入RealmDB的代码如下所示:
func jsonAdd() {
if let path = Bundle.main.path(forResource: "Data", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = JSON(data)
for (index,subJson):(String, JSON) in json {
do {
try realm.write {
realm.create(Item.self, value: subJson, update: .modified)
}
} catch let error as NSError {
print("Unable to write")
print(error)
}
}
} catch {
print("Error")
}
}
}
我认为这个问题是一个JSON映射,但任何帮助将非常感谢将JSON写入到Realm DB,包括流派作为列表。
NB:在' write '函数之前,我已经设法使用以下代码(基于Realm文档)写到Realm DB,但似乎无法让它为我的JSON结构工作。
let newdata = "{"id": 0, "name": "Car", "genres": ["Fantasy","General"], "viewable": true, "weapon": false, "vehicle": true}".data(using: .utf8)!
let json = try! JSONSerialization.jsonObject(with: newdata, options: [])
谢谢!
通过以下方法解决:
-
对JSON结构进行如下修改:
[ { "id": 0, "name": "Car", "genres": ["Fantasy", "General"], "viewable": true, "weapon": false, "vehicle": true }, { "id": 1, "name": "Truck", "genres": ["Fantasy", "General"], "viewable": true, "weapon": false, "vehicle": true } ]
-
创建一个新的流派对象,以更好地处理列表
class Genres: Object { @objc dynamic var id = 0 @objc dynamic var name = "" override static func primaryKey() -> String? { return "id" } } class Item: Object { @objc dynamic var id = 0 @objc dynamic var name = "" var genres = List<Genres>() @objc dynamic var viewable: Bool = false @objc dynamic var weapon: Bool = false @objc dynamic var vehicle: Bool = false override static func primaryKey() -> String? { return "id" } override static func indexedProperties() -> [String] { return ["genres", "viewable"] } }
3)关键的是,在jsonADD函数中更新了代码以创建一个新的Item Object,然后在尝试写入Realm DB之前将JSON值映射到该对象:
for (key,subJson):(String, JSON) in jsonObjects {
let thisItem = Item()
thisItem.id = subJson["id"].intValue
thisItem.name = subJson["name"].stringValue
thisItem.visable = subJson["viewable"].boolValue
thisItem.weapon = subJson["weapon"].boolValue
thisItem.vehicle = subJson["vehicle"].boolValue
let genreArray = subJson["genres"].arrayValue
for genre in genreArray {
let string = genre.stringValue
let predicate = NSPredicate(format: "name = %@", string)
if let foundGenre = realm.objects(Genres.self).filter(predicate).first {
thisItem.genres.append(foundGenre)
}
}
do {
try realm.write {
realm.create(Item.self, value: thisItem, update: .modified)
}
} catch let error as NSError {
print("Unable to write")
print(error)
}
}