2017-09-15 58 views
1

我努力让我的CoreData对象到JSON,以便我可以使用它发送到Web服务器。在Swift 3中JSON CoreData对象

这是如何我目前从CoreData取我的对象:

func fetchRecord() -> [Record] { 

    do { 
     records = try context.fetch(Record.fetchRequest()) 

    } catch { 
     print("Error fetching data from CoreData") 
    } 
    return records 
} 

我能够上显示这对我的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 
} 

我试图环路我的要求内像这样:

for rec in records { 
    print(rec) 
} 

给出了这个:

enter image description here

我已经阅读了很多关于如何实现这个目标的方法,但是没有一个看起来真的对我有益。这里的大多数示例都显示了如何将JSON转换为CoreData,而不是其他方式。有谁知道任何可以帮助我实现这个目标的好教程或文档?

回答

0

您可以通过下面的代码

let record = recArray[index] 
     let keys = Array(record.entity.attributesByName.keys) 
     let dict = record.dictionaryWithValues(forKeys: keys) 

后,您可以使用jsonserialization到字典转换成JSON对象

do{ 
     let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) 
     let reqJSONStr = String(data: jsonData, encoding: .utf8) 
     print(reqJSONStr!) 
    }catch{ 

    } 

希望这将有助于您NSManageObject子类对象转换成字典。

+0

对不起,请查看更新的标题。有什么办法可以将它转换成Swift吗? – Chace

+0

您能否解释我会在哪里使用此代码? – Chace

+0

请检查swift版本,根据您的规范要发送此记录对象到webservice,为此,您要将recort对象转换为json。因此,只需将此添加到要将coredata对象inti json转换的位置即可。 – KavyaKavita

0

如果你愿意,你可以使用以下获得从核心数据字典格式结果:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Record") 
fetchRequest.resultType = .dictionaryResultType 
do { 
    records = try context.fetch(fetchRequest) 
} catch { 
    print("Error fetching data from CoreData") 
} 
+0

我收到一个错误,说_Cannot不能指定类型'[Any]'的值来键入'[Record]'_,并且当我将其更改为:'records = try context.fetch(fetchRequest)as! [Record]'我得到这个错误_Could不能将类型'NSKnownKeysDictionary1'(0x10639caf8)的值转换为Core_Data_App.Record'(0x1055a9360)._ – Chace