我需要使用一些mapper(例如Object Mapper)将检索到的JSON Object保存到Core Data中。 我使用了一个可以检索这个json的rest api:
[
{
"event_id": "1",
"event_name": "Lungo il tevere",
"event_image_url": "https:\/\/www.dayroma.it\/wp-content\/uploads\/2016\/06\/event_fb-9400.jpg",
"event_content": "<b>Lungo il Tevere Roma 2016, bancarelle sulle banchine del Tevere<\/b>\r\n\r\n \r\n\r\n ",
"event_start_date": "2016-07-29",
"event_end_date": "2016-07-30",
"event_start_time": "22:00:00",
"event_end_time": "03:00:00",
"location_name": "Lungotevere",
"location_address": "Piazza Navona 2, Roma",
"location_latitude": "41.897785",
"location_longitude": "12.472971"
},
{
"event_id": "8",
"event_name": "test 7 - VIlla BOrghese",
"event_image_url": "https:\/\/www.dayroma.it\/wp-content\/uploads\/2016\/06\/event_fb-9398.jpg",
"event_content": "TEst villa borghese",
"event_start_date": "2016-07-29",
"event_end_date": "2016-07-30",
"event_start_time": "22:00:00",
"event_end_time": "02:00:00",
"location_name": "Villa Borghese",
"location_address": "Villa Borghese 4, Roma",
"location_latitude": "41.912888",
"location_longitude": "12.485208"
}
没什么特别的,一个简单的JSON数组。 我需要将其解析为数据对象并存储到Core Data中。 实际上,我有关于将Object映射到Core Data Object的问题,因为只检索String值,其他的都是nil。
这是我的dataController
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
override init() {
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}
}
}
这是我的对象核心属性:
extension Event {
@NSManaged var eventId: Int
@NSManaged var eventName: String?
@NSManaged var eventImageUrl: String?
@NSManaged var eventContent: String?
@NSManaged var eventStartTime: NSDate?
@NSManaged var eventEndTime: NSDate?
@NSManaged var eventStartDate: NSDate?
@NSManaged var eventEndDate: NSDate?
@NSManaged var locationName: String?
@NSManaged var locationAddress: String?
@NSManaged var locationLatitude: NSNumber?
@NSManaged var locationLongitude: NSNumber?
}
这是我实现mappable的核心数据对象模型:
class Event: NSManagedObject, Mappable {
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: DataController().managedObjectContext)
}
required init?(_ map: Map) {
let ctx = DataController().managedObjectContext
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: ctx)
super.init(entity: entity!, insertIntoManagedObjectContext: ctx)
mapping(map)
}
func mapping(map: Map) {
eventId <- map["event_id"]
eventName <- map["event_name"]
eventImageUrl <- map["event_image_url"]
eventContent <- map["event_content"]
eventStartTime <- map["event_start_time"]
eventEndTime <- map["event_end_time"]
eventStartDate <- map["event_start_date"]
eventEndDate <- map["event_end_date"]
locationName <- map["location_name"]
locationAddress <- map["location_address"]
locationLatitude <- map["location_latitude"]
locationLongitude <- map["location_longitude"]
}
}
运行此:
let URL = "##### MY API ######"
Alamofire.request(.GET, URL).responseArray { (response: Response<[Event], NSError>) in
let eventsArray = response.result.value
for element in eventsArray! {
print(element)
}
}
我找回了这个:
data: {
eventContent = "TEst villa borghese";
eventEndDate = nil;
eventEndTime = nil;
eventId = 0;
eventImageUrl = "https://www.dayroma.it/wp-content/uploads/2016/06/event_fb-9398.jpg";
eventName = nil;
eventStartDate = nil;
eventStartTime = nil;
locationAddress = "Villa Borghese 4, Roma";
locationLatitude = nil;
locationLongitude = nil;
locationName = "Villa Borghese";
}
大部分领域都是零, 你能帮我理解是什么问题吗?
谢谢你
答案 0 :(得分:0)
即使你在等待NSNumber或NSDate,你也只能收到Json。
要使此地图有效,您应该使用ObjectMapper中的自定义变换,并按照以下方式设置映射:
birthday <- (map["birthday"], DateTransform())
或进行自定义转换,例如:
private static let formatter: NSNumberFormatter = NSNumberFormatter()
private let transform = TransformOf<NSNumber, String>(fromJSON:
{ (value: String?) -> NSNumber? in
// transform value from String? to Int?
formatter.numberStyle = .DecimalStyle
return formatter.numberFromString(value!)
}, toJSON:
{ (value: NSNumber?) -> String? in
// transform value from Int? to String?
if let value = value
{
return String(value)
}
return nil
})
并使用它:
people <- (map["people"], transform)
希望得到这个帮助。