核心数据NSManagedObject转换为json格式

时间:2018-08-11 12:05:20

标签: core-data swift4

大家好,我需要您的帮助,我现在是快速的语言新手,我在这里需要从核心数据结果中获取这种格式的json。预先感谢

Core Data Function返回此结果,我想将此结果信息转换为json格式

func GetAttendance()->[Tbl_Attendance]
    {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Tbl_Attendance")

        do {
            let fetchedAttendance = try context.fetch(fetchRequest) as! [Tbl_Attendance]
            return fetchedAttendance
        } catch {
            fatalError("Failed to fetch Tbl_Attendance: \(error)")
        }
    }

我需要这样转换

{
    "students": [
        {
            "id": 12345,
            "name": "Giuseppe",
            "lastName": "Lanza",
            "age": 31
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

  • 创建Tbl_Attendance的扩展名并使其实现Encodable
  • 在扩展名中创建enum CodingKeys: String, CodingKey {...},其中包含所有要编码的属性
  • 扩展public func encode(to encoder: Encoder)的实现
  • 从代码中的某处执行编码

示例

extension Tbl_Attendance: Encodable {
  enum CodingKeys: String, CodingKey {
    case prop1
    case prop2
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(prop1, forKey: .prop1)
    try container.encode(prop2, forKey: .prop2)
  }
}

//perform encoding somewhere in your code
let arr: GetAttendance() 
let encoder = JSONEncoder()
do {
    let json = try encoder.encode(arr)
    //print(String(data: json, encoding: .utf8)!)
} catch {
    print("JSON error \(error)")
}