gpt4 book ai didi

ios - 以编程方式快速编写 JSON 文件

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:53 24 4
gpt4 key购买 nike

我正在制作测验应用程序,我想从服务器下载 JSON 文件中的问题,解析它并制作我将展示的问题对象。我这样做了,所以现在我想制作一个将创建 JSON 文件并将其上传到服务器的应用程序,我希望它看起来像这样
enter image description here

我将从文本字段中获取所有信息并将其保存在像这样的 JSON 文件中(带有 oder 值)

    [
{
"question":"If you want to create a custom class which can be displayed on the view, you can subclass UIView.",
"answers":["True", "False"],
"correctIndex":0,
"module":3,
"lesson":0,
"feedback":"Subclassing UIView gives your class the methods and properties of a basic view which can be placed onto the view."
}
]

swift 是否有我可以使用的具有功能的框架?或者我必须手动制作?如果手动如何保存 JSON 文件?

最佳答案

您可以为此目的使用 JSONSerialization 类。请查看下面在 Playground 中制作的代码片段

import Foundation

// Dictionary containing data as provided in your question.
var dictonary : [String : Any] = ["question":"If you want to create a custom class which can be displayed on the view, you can subclass UIView.",
"answers":["True", "False"],
"correctIndex":0,
"module":3,
"lesson":0,
"feedback":"Subclassing UIView gives your class the methods and properties of a basic view which can be placed onto the view."
]


if let jsonData = try JSONSerialization.data(withJSONObject: dictonary, options: .init(rawValue: 0)) as? Data
{
// Check if everything went well
print(NSString(data: jsonData, encoding: 1)!)

// Do something cool with the new JSON data
}

如果您在 Xcode playground 中运行此代码,您可以看到以 JSON 格式打印的数据获得 JSON 后,您可以使用您选择的网络库将数据发送到服务器。

关于ios - 以编程方式快速编写 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42550657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com