Cha*_*ace 2 json core-data ios
我正在努力将我的CoreData对象转换为JSON,以便我可以使用它发送到Web服务器.
这就是我目前从CoreData获取对象的方式:
func fetchRecord() -> [Record] {
do {
records = try context.fetch(Record.fetchRequest())
} catch {
print("Error fetching data from CoreData")
}
return records
}
Run Code Online (Sandbox Code Playgroud)
我可以通过这种方式显示在我的tableView上:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recordCell", for: indexPath) as! RecordCell
cell.nameLbl.text = records[indexPath.row].name
cell.quantityLbl.text = "Quantity: \(String(records[indexPath.row].quantity))"
cell.dateLbl.text = dateString(date: records[indexPath.row].date)
return cell
}
Run Code Online (Sandbox Code Playgroud)
我试图在我的请求中循环,如下所示:
for rec in records {
print(rec)
}
Run Code Online (Sandbox Code Playgroud)
这给出了:
我已经阅读了很多关于实现这一目标的方法,但它们似乎都没有对我有益.大多数示例都显示了如何将JSON提供给CoreData而不是其他方式.有谁知道任何可以帮助我实现这一目标的好教程或文档?
Mik*_*lty 10
这里将代码作为扩展。基于 KavyaKavita 的回答。
extension NSManagedObject {
func toJSON() -> String? {
let keys = Array(self.entity.attributesByName.keys)
let dict = self.dictionaryWithValues(forKeys: keys)
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let reqJSONStr = String(data: jsonData, encoding: .utf8)
return reqJSONStr
}
catch{}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let jsonString = YourCoreDataObject.toJSON()
print(jsonString)
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码将 NSManageObject 子类对象转换为字典
let record = recArray[index]
let keys = Array(record.entity.attributesByName.keys)
let dict = record.dictionaryWithValues(forKeys: keys)
Run Code Online (Sandbox Code Playgroud)
之后,您可以使用 jsonserialization 将该字典转换为 json 对象
do{
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let reqJSONStr = String(data: jsonData, encoding: .utf8)
print(reqJSONStr!)
}catch{
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助。
在Swift 4中,您可以利用Encodable协议并将功能直接添加到Core Data对象.
假设你的NSManagedObject子类扩展看起来像
extension Record {
@NSManaged public var date: Date
@NSManaged public var name: String
@NSManaged public var quantity: Int32
@NSManaged public var synched: Bool
@NSManaged public var uuid: String
...
Run Code Online (Sandbox Code Playgroud)
采用 Encodable
extension Record : Encodable {
Run Code Online (Sandbox Code Playgroud)
并添加
private enum CodingKeys: String, CodingKey { case date, name, quantity, synched, uuid }
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(date, forKey: .date)
try container.encode(name, forKey: .name)
try container.encode(quantity, forKey: .quantity)
try container.encode(synched, forKey: .synched)
try container.encode(uuid, forKey: .uuid)
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以轻松地将记录编码为JSON
do {
records = try context.fetch(Record.fetchRequest())
let jsonData = try JSONEncoder().encode(records)
} catch {
print("Error fetching data from CoreData")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3118 次 |
| 最近记录: |