繁体   English   中英

在 Swift 中使用 swiftyJSON 成功将 JSON 写入 Realm DB

[英]Successfully write JSON to Realm DB using swiftyJSON in Swift

我正在尝试从 JSON 文件(使用 swiftyJSON)写入 Realm DB 得到以下错误:

libc++abi.dylib:以 NSException 类型的未捕获异常终止 *** 由于未捕获异常“RLMException”而终止应用程序,原因:“无效值”{“vehicle”:true,“viewable”:true,“id”: 0, "weapon": false, "genres": "[Fantasy, General]", "name": "Car" }' 初始化'Item'类型的object:缺少键'id''

我的 JSON 文件结构如下:

  [
  {
    "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
  },
]

我的 Realm DB Class 是:

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: I've managed to write to the Realm DB using the following code (based off the Realm documentation) before the 'Write' function but cannot seem to get it to work for my JSON structure.

 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: [])

谢谢!

通过以下方法解决:

  1. 对我的 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 } ]
  2. 创建了一个新的流派 Object 以更好地处理列表

     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)Crucially in the jsonADD function updated the code to create a new Item Object then mapped the JSON values to that object before attempting to write to the Realm DB:

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)
        }
    }

暂无
暂无

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

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