首页 > 解决方案 > 来自 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

标签: arraysswiftmultidimensional-array

解决方案


从 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"
    }
}

看看这个教程


推荐阅读