我的json数据格式如下:
{
"AvailToDate": "2016-12-31 00:00:00.0",
"CompanyName": "Google",
"ShowroomName": "Mobile Phones",
"OwnerUserId": "OID1544234",
"PartyId": "APL026306123",
"Currency": "USD",
"ProductCount": 10,
"AvailFromDate": "2016-12-20 00:00:00.0",
"MaxPrice": 10,
"MinPrice": 1,
"ShowroomId": 11904,
"AccessStatus": "Open"
}
我能够将上述对象的数组转换为Dictionary对象的数组。然后我将字典对象转换为核心数据实体。
这是我将Dictionary对象转换为ManagedObject的代码
let showroom = Showroom(context: bgContext)
showroom.availableFromDate = (tShowroom[kAvailFromDate] as? String)?.toDate()
showroom.minPrice = tShowroom[kMinPrice] as? Float
showroom.showroomID = tShowroom[kShowroomId] as! Int32
showroom.accessStatus = tShowroom[kAccessStatus] as? String
showroom.availableToDate = (tShowroom[kAvailToDate] as? String)?.toDate()
showroom.companyName = tShowroom[kCompanyName] as? String
showroom.showroomName = tShowroom[kShowroomName] as? String
showroom.ownerID = tShowroom[kOwnerUserId] as? String
showroom.partyID = tShowroom[kPartyId] as? String
showroom.currency = tShowroom[kCurrency] as? String
showroom.productsCount = tShowroom[kProductCount] as! Int32
showroom.maxPrice = tShowroom[kMaxPrice] as? Float
如果收到的某些参数缺少JSON,我们如何解析该对象。我是否必须将ManagedObject中的所有参数设置为Optional? 我不想使用"如果让"或"警卫"对于每个参数。什么是实现它的最佳方式?
答案 0 :(得分:0)
您只需使用??
语法
假设您想将最低价格设置为10.2如果没有来自json的值返回,请执行以下操作:
showroom.minPrice = tShowroom[kMinPrice] as? Float ?? 10.2
或者字符串:
showroom.accessStatus = tShowroom[kAccessStatus] as? String ?? "Default String"
答案 1 :(得分:0)
我建议您在optional
型号上将每个参数设置为Showroom
。这样更安全。
此外,您可能会为您的模型引入一些转换相关类,您可以在其中执行guard
- if let
检查,而您只需处理错误。
如下所示:
import Foundation
import UIKit
enum DictionaryParseError: Error {
case missingKey
case invalidType
}
extension Dictionary where Key: ExpressibleByStringLiteral {
// You are expecting an optinal string
func string(key: Key) -> String? {
return self[key] as? String
}
// You are expecting an optinal float
func float(key: Key) -> Float? {
return self[key] as? Float
}
// You are expecting a string
func requiredString(key: Key) throws -> String {
let string = try self.requiredValue(key) as String
return string
}
// You are expecting a float
func requiredFloat(key: Key) throws -> Float {
let float = try self.requiredValue(key) as Float
return float
}
private func requiredValue<Type>(_ key: Key) throws -> Type {
guard let value = self[key] else {
throw DictionaryParseError.missingKey
}
guard let typedValue = value as? Type else {
throw DictionaryParseError.invalidType
}
return typedValue
}
}
答案 2 :(得分:0)
如果您没有其中一个托管对象属性的值,则有两种选择:
您做出的选择完全取决于您计划如何使用数据以及是否存在任何合理的默认值。你不必以同样的方式处理每一处房产。