【问题标题】:SwiftUI List from Json Array来自 Json 数组的 SwiftUI 列表
【发布时间】:2020-10-20 02:46:21
【问题描述】:

我正在尝试获取我从 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

【问题讨论】:

  • 你能分享你的 Json 数组吗?
  • 我发布的代码就是它,我只是将实际值替换为它们的类型并将其压缩为两个条目。
  • @MatthewPrice - 将值替换为类型名称有点奇怪。你的意思是你有一个像这样的对象:{ "data": [ [1,"foo"], [2, "bar", 3]] },你想解码成一个数组吗? [[Any]]?

标签: arrays swift multidimensional-array


【解决方案1】:

从 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”,您可以更改变量的名称,但您需要明确告知例如快速

struct Response: Codable {
    var otherVariableName: [[String]]
    
    enum CodingKeys: String, CodingKey {
        case otherVariableName = "data"
    }
}

看看这个tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多