大家好,我需要您的帮助,我现在是快速的语言新手,我在这里需要从核心数据结果中获取这种格式的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
}
]
}
答案 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)")
}