使用领域和结果 JSON
Posted
技术标签:
【中文标题】使用领域和结果 JSON【英文标题】:Working with Realm and result JSON 【发布时间】:2017-08-15 06:51:25 【问题描述】:我是领域的新手,我正在尝试在我的项目中使用领域。在这里,我试图解析 JSON 并使用领域保存它。当我试图循环遍历结果数组时发生错误
'尝试在写入事务之外修改对象 - 首先在 RLMRealm 实例上调用 beginwritetransaction'
这是 JSON 结果:
"data":["id":1,"parent_id":0,"name":"JenniferMaenle","title":"Ms","phone":"","address":"Toled, ohio","email":"jlmaenle@aol.com","image":"44381525_2017.jpg","relation_id":5,"created_at":null,"updated_at":"2017-08-10 02:30:05","id":2, "parent_id":1,"name":"Khadeeja","title":"","phone":"","address":"","email":"","image":"Khadeeja_2017-07-17.jpg","relation_id":2,"created_at":null,"updated_at":"2017-07-17 08:3:12"]
我正在尝试解析 JSON 并将其保存在 Realm 数据库中。这是我的尝试:
class Person: Object
dynamic var name = ""
dynamic var title = ""
dynamic var address = ""
override func viewDidLoad()
super.viewDidLoad()
self.add()
func add()
guard let data = dataFromFile("ServerData") else return
let persons = Person()
do
if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject]
if let data = json["data"] as? [[String:AnyObject]]
for eachItem in data
persons.name = eachItem["name"] as! String
persons.title = eachItem["title"] as! String
persons.address = eachItem["address"] as! String
try! realm.write
realm.add(persons)
catch
print("Error deserializing JSON: \(error)")
【问题讨论】:
【参考方案1】:不要修改persons
对象并将其再次添加到领域。您看到的错误是因为您将人员添加到领域,然后在 for eachItem in data
的第二次迭代中再次对其进行编辑。 Persons
已在此迭代中添加到领域,您尝试在领域写入事务之外为其指定一个新名称。这就是您看到错误的原因。最好为每个人创建一个新对象。
func add()
guard let data = dataFromFile("ServerData") else return
do
if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject]
if let data = json["data"] as? [[String:AnyObject]]
for eachItem in data
let persons = Person()
persons.name = eachItem["name"] as! String
persons.title = eachItem["title"] as! String
persons.address = eachItem["address"] as! String
try! realm.write
realm.add(persons)
catch
print("Error deserializing JSON: \(error)")
【讨论】:
谢谢@Yannick 工作完美:)【参考方案2】:如错误所示,您需要在写入中执行事务,
一种选择是单独写每个人:
for eachItem in data
let person = Person()
person.name = eachItem["name"] as! String
person.title = eachItem["title"] as! String
person.address = eachItem["address"] as! String
try! realm.write
realm.add(person)
第二种选择是构建一个对象,然后编写:
for eachItem in data
let person = Person();
person.name = eachItem["name"] as! String
person.title = eachItem["title"] as! String
person.address = eachItem["address"] as! String
persons.add(person)
try! realm.write
realm. append(persons)
您可能需要对此进行一些更改,但这就是我们的想法。
【讨论】:
以上是关于使用领域和结果 JSON的主要内容,如果未能解决你的问题,请参考以下文章