arrays - 来自 Json 数组的 SwiftUI 列表
问题描述
我正在尝试获取我从 JSON 解码的信息并将其放入列表中。我一直在使用 SwiftyJSON 来实际获取它,但我很难实际使用它。我已经尝试了几个教程,但没有运气,我对 Swift 还是很陌生,但 JSON 被证明特别困难。
为了澄清,我使用 URLSession 从 URL 中获取了数据
guard let data = data else { return }
do {
//print(data)
//outputs 500 bytes
let json = try JSON(data: data)
//print(json)
//out puts the JSON Below
} catch {
print(error)
}
这是JSON
{
"data" : [
[
"0",
"this is a string",
"this is a string",
"this is a string",
"1",
"1",
"1",
"1",
"this is a string",
"1"
],
[
"Int",
"this is a string",
"this is a string",
"this is a string",
"4",
"3",
"7",
"6",
"this is a string",
"5"
],
[
"0",
"this is a string",
"this is a string",
"this is a string",
"1",
"1",
"1",
"1",
"this is a string",
"1"
]]}
我的目标是将这个日期输出到一个视图中,其中每个数组是一行,军队中的每个字符串都是一个列。
COLUMN COLUMN COLUMN COLUMN COLUMN COLUMN COLUMN COLUMN COLUMN COLUMN
ROW 0 hi hi hi 1 0 0 0 0 0
ROW 0 hi hi hi 1 0 0 0 0 0
ROW 0 hi hi hi 1 0 0 0 0 0
ROW 0 hi hi hi 1 0 0 0 0 0
解决方案
从 Swift 3(如果我没记错的话)你有一个 Json 编码器/解码器
尽管您的 Json 对我来说似乎有点奇怪,但它是一个有效且相当容易复制的 Json,因为它仅包含一个包含字符串数组数组的字段,如果所有值都带有“”,则它们被视为字符串。
在这种情况下,只需创建一个与您的 json 匹配的结构,它将是这样的
// Struct matching your Json
struct Response: Codable {
var data: [[String]]
}
// How to read
let jsonData: Data? = yourJsonString.data(using: .utf8)
let decoder = JSONDecoder()
if let callResult = try? decoder.decode(Response.self, from: jsonData!) {
// your code here
} else {
// something went wrong
}
现在这个结构与你的 Json 文件完全匹配,如果你的文件不是这样,你可能需要调整它。
结构中的变量必须与 json 字段匹配,例如在您的 json 中,您有字段“data”,那么您的结构必须包含变量“data”,您可以更改变量的名称,但您需要明确告诉 swift
struct Response: Codable {
var otherVariableName: [[String]]
enum CodingKeys: String, CodingKey {
case otherVariableName = "data"
}
}
看看这个教程
推荐阅读
- api - 谷歌地理编码 API 返回错误的邮编/城市
- java - 在旋转和阻塞时间短或没有旋转和阻塞时间的安全点操作期间,什么可能导致非常高的同步时间?
- c - 传递参数以更改 #define 变量
- ruby-on-rails - 虾 PDF 导致 heroku rails 应用程序中的内存膨胀
- php - 如果序列化失败,PHP 重试 PDO 执行:1213 尝试获取锁时发现死锁
- caching - NHibernate 二级缓存:查询缓存无法按预期工作
- build - 如何以角度更改构建项目的路径?
- python - 如何解决“变量在检查点可用,但与模型变量的形状不兼容”?
- java - JSP 没有为 HTML 表单 POST 显示正确的 UTF-8 内容
- javascript - 在同一个嵌套选择器中获取当前悬停/鼠标悬停元素