如何使用Swift将存储的值转换为JSON格式? [英] How to convert stored values to JSON format using Swift?
问题描述
我正在尝试将存储的 coredata
值转换为 JSON
格式,并且JSON格式值需要分配一个变量,因为此生成的JSON需要发送到服务器。下面的代码我尝试获取coredata存储的值,但不知道如何生成JSON所需的格式。
从coredata获取值
let context =(UIApplication.shared.delegate as!AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest< NSFetchRequestResult>(实体名称:用户)
做{
让结果=尝试context.fetch(fetchRequest)
让dateCreated =结果为! [Userscore]
for dateCreated中的_datecreated {
print( \(_datecreated.id!)-\(_datecreated.name!))//输出:79-b \n 80- c \n 78-a
}
}捕获让err作为NSError {
print(err.debugDescription)
}
需要将Coredata值转换为JSON格式以下
{
状态:true,
数据:[[
} id: 20,
的名称: a
},
{
。 id: 21,
。
id: 22,
名称: c
}
}
}
您可以使用 Encodable
的属性来制作发生这种情况。这样做还有一个好处,就是不求助于 Any
类型。
对于JSON,您可以使用以下命令类型:
struct JSONMessage:可编码{
var状态:Bool
var数据:[JSONDataEntry]
}
结构体JSONDataEntry:可编码{
var id:字符串
变量名称:字符串
}
然后您可以按以下方式调整您的do / try / catch:
< pre class = lang-swift prettyprint-override>
do {
let results = try context.fetch(fetchRequest)
let dateCreated =结果为! [用户评分]
// //从这里开始*
let data = dateCreated.map {JSONDataEntry(id:String($ 0.id!),name:$ 0.name!)}}
let状态= true //<--不确定状态来自何处,因此在此处添加
let message = JSONMessage(status:status,data:data)
let jsonData =试试JSONEncoder()。encode(message)
if let json = String(data:jsonData,编码:.utf8){
//使用JSON字符串
print(json)
}
/ / *在这里结束*
}捕获let err作为NSError {
print(err.debugDescription)
}
I am trying to convert stored coredata
values to JSON
format and the JSON format value need to assign a single variable, because this generated JSON I need to send to server. Below code I tried to get coredata stored values but don’t know how to generate JSON required format.
Getting values from coredata
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do {
let results = try context.fetch(fetchRequest)
let dateCreated = results as! [Userscore]
for _datecreated in dateCreated {
print("\(_datecreated.id!)-\(_datecreated.name!)") // Output: 79-b \n 80-c \n 78-a
}
} catch let err as NSError {
print(err.debugDescription)
}
Need to Convert Coredata Value to Below JSON format
{
"status": true,
"data": [
{
"id": "20",
"name": "a"
},
{
"id": "21",
"name": "b"
},
{
"id": "22",
"name": "c"
}
]
}
You can use the properties of an Encodable
to make this happen. This has the added benefit of not resorting to the Any
type.
For the JSON, you could use the following types:
struct JSONMessage: Encodable {
var status: Bool
var data: [JSONDataEntry]
}
struct JSONDataEntry: Encodable {
var id: String
var name: String
}
Then you can adjust your do/try/catch as follows:
do {
let results = try context.fetch(fetchRequest)
let dateCreated = results as! [Userscore]
// *starting here*
let data = dateCreated.map { JSONDataEntry(id: String($0.id!), name: $0.name!) }
let status = true // <- not sure where status comes from, so adding here
let message = JSONMessage(status: status, data: data)
let jsonData = try JSONEncoder().encode(message)
if let json = String(data: jsonData, encoding: .utf8) {
// do something with the JSON string
print(json)
}
// *ending here*
} catch let err as NSError {
print(err.debugDescription)
}
这篇关于如何使用Swift将存储的值转换为JSON格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!