2017-09-15 62 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