将数据从 JSON 保存到 Realm
Posted
技术标签:
【中文标题】将数据从 JSON 保存到 Realm【英文标题】:Saving data from JSON to Realm 【发布时间】:2016-04-11 18:56:32 【问题描述】:我是 Realm 新手,尝试将 JSON 数据从 WebService 保存到我的 Realm DB 时遇到了一些麻烦。
这是 JSON:
"Programacao":[
"Dia":"5",
"Idp":"1833",
"Programa":"T\u00e1 Na Hora",
"Inicio":"06:00",
"Final":"08:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1834",
"Programa":"Bom dia Chiru",
"Inicio":"08:00",
"Final":"09:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1835",
"Programa":"Conex\u00e3o",
"Inicio":"09:00",
"Final":"11:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1836",
"Programa":"As Mais Pedidas",
"Inicio":"11:00",
"Final":"12:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1837",
"Programa":"Casa da Sogra",
"Inicio":"12:00",
"Final":"13:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1838",
"Programa":"Canal Livre",
"Inicio":"13:00",
"Final":"15:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"18",
"Programa":"Batid\u00e3o da Chiru",
"Inicio":"15:00",
"Final":"17:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1827",
"Programa":"Sul Bandas",
"Inicio":"17:00",
"Final":"19:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1828",
"Programa":"Voz do Brasil",
"Inicio":"19:00",
"Final":"20:00",
"Data":"08\/04\/2016"
,
"Dia":"5",
"Idp":"1831",
"Programa":"Al\u00f4 Chiru",
"Inicio":"20:00",
"Final":"23:59",
"Data":"08\/04\/2016"
]
我创建了以下结构:
领域对象类:
import Foundation
import RealmSwift
class ROListing: Object // Programação da Rádio
dynamic var id = 0
dynamic var showName = ""
dynamic var showId = ""
dynamic var showStartTime = ""
dynamic var showEndTime = ""
dynamic var showNumericDate = ""
dynamic var showDate = ""
override static func primaryKey() -> String?
return "id"
对象操作类:
import Alamofire
import SwiftyJSON
import Foundation
class Listing: ResponseJSONObjectSerializable
var showName :String? // nomePrograma
var showId :String? // idp
var showStartTime :String? // inicioPrograma
var showEndTime :String? // finalPrograma
var showNumericDate :String? // dia
var showDate :String? // data
required init?(json: JSON)
self.showName = json["Programa"].string
self.showId = json["Idp"].string
self.showStartTime = json["Inicio"].string
self.showEndTime = json["Final"].string
self.showNumericDate = json["Dia"].string
self.showDate = json["Data"].string
required init()
class ListingArray: ResponseJSONObjectSerializable
var showArray: [Listing]? // Programacao
required init?(json: JSON)
if let arrayJson = json["Programacao"].array
self.showArray = []
for json in arrayJson
let instance = Listing(json: json)
self.showArray?.append(instance!)
required init()
通过以下方式与 WebService 连接:
func getRadioListing(success: () -> ())
guard let url = apiController.createURLWithComponentsForListingsWith(appId: "63") else
print("Invlaid URL!")
return
print(url)
Alamofire.request(.GET, url).responseObject
(response: Response<ListingArray, NSError>) in
if let jsonResults = response.result.value
self.listings = jsonResults
for listing in self.listings.showArray!
RealmObjectManager.sharedInstance.createUpdateDB(withListing: listing)
success()
else
print("Error parsing JSON!")
return
最后,将对象实际保存到 Realm DB 的方法。
func createUpdateDB(withListing listing: Listing)
print(Realm.Configuration.defaultConfiguration.path!)
if self.listingArray.count == 0
do
try self.realm.write
let newListing = ROListing()
newListing.showName = listing.showName!
newListing.showId = listing.showId!
newListing.showStartTime = listing.showStartTime!
newListing.showEndTime = listing.showEndTime!
newListing.showNumericDate = listing.showNumericDate!
newListing.showDate = listing.showDate!
self.realm.add(newListing)
catch let error as NSError
print("Error creating Listing DB: \(error.userInfo)")
但是,我无法将所有节目都放入数据库。有人可以帮我吗?
提前致谢!
【问题讨论】:
Cole 可能已经在这里解决了问题,但以防万一,您能否发布您在尝试插入所有节目时收到的错误日志?谢谢! 是的,我的逻辑有问题!我没有收到任何错误,但只有第一个元素 [0] 被保存。我想我需要先检查我的listingArray 是否为空(或nil?),然后执行写入。谢谢科尔坎贝尔。 【参考方案1】:如果没有错误日志,我不能肯定地说,但是由于主键,您确实会遇到问题。领域强制主键的唯一性,因此如果您尝试将具有相同主键的对象添加到领域,与现有相同类型的对象将破坏。据我所知,默认情况下您将主键设置为 0,但在保存之前您没有使用唯一值对其进行更新。
如果您只需要每个对象的唯一标识符并且顺序无关紧要,这是一个很好的解决方案:
dynamic var id: String = NSUUID().UUIDString
【讨论】:
以上是关于将数据从 JSON 保存到 Realm的主要内容,如果未能解决你的问题,请参考以下文章
将文本从 UITextView 保存到领域(Swift 5)时出现问题