繁体   English   中英

如何在 Swift 中将 JSON 数组解析为数组

[英]How to parse Array of JSON to array in Swift

我正在尝试解析如下所示的 JSON

[
  {
    "People": [
      "Jack",
      "Jones",
      "Rock",
      "Taylor",
      "Rob"
    ]
  },
  {
    "People": [
      "Rose",
      "John"

    ]
  },
  {
    "People": [
      "Ted"
    ]
  }
]

到一个数组,结果是:

[ ["Jack", "Jones", "Rock", "Taylor", "Rob"] , ["Rose", "John"], ["Ted"] ]

这是数组的数组。

我尝试使用下面的代码

if let path = Bundle.main.path(forResource: "People", ofType: "json") {
    let peoplesArray = try! JSONSerialization.jsonObject(
            with: Data(contentsOf: URL(fileURLWithPath: path)),
            options: JSONSerialization.ReadingOptions()
    ) as? [AnyObject]
    for people in peoplesArray! {
        print(people)
    }
}

当我打印“人”时,我得到 o/p 作为

{
  People = (
    "Jack",
    "Jones",
    "Rock",
    "Taylor",
    "Rob"
  );
}
{
  People = (
    "Rose",
    "John"
  );
}
...

当“People”重复 3 次时,我很困惑如何解析

尝试在 UITableView 中显示内容,其中我的第一个单元格有“Jack”..“Rob”,第二个单元格有“Rose”、“John”,第三个单元格为“Ted”

请帮助我了解如何实现这一目标

您可以利用 Swift 4Decodable以优雅且类型安全的方式执行此操作

首先为您的 people 数组定义一个类型。

struct People {
  let names: [String]
}

然后将其Decodable ,以便可以使用 JSON 对其进行初始化。

extension People: Decodable {

  private enum Key: String, CodingKey {
    case names = "People"
  }

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Key.self)

    self.names = try container.decode([String].self, forKey: .names)
  }
}

现在您可以轻松解码您的 JSON 输入

guard
  let url = Bundle.main.url(forResource: "People", withExtension: "json"),
  let data = try? Data(contentsOf: url)
else { /* Insert error handling here */ }

do {
  let people = try JSONDecoder().decode([People].self, from: data)
} catch {
  // I find it handy to keep track of why the decoding has failed. E.g.:
  print(error)
  // Insert error handling here
}

最后得到你可以做的名字的线性数组

let names = people.flatMap { $0.names }
// => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]
 var peoplesArray:[Any] = [
    [
        "People": [
        "Jack",
        "Jones",
        "Rock",
        "Taylor",
        "Rob"
        ]
    ],
    [
        "People": [
        "Rose",
        "John"

        ]
    ],
    [
        "People": [
        "Ted"
        ]
    ]
  ]

 var finalArray:[Any] = []

 for peopleDict in peoplesArray {
    if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
        finalArray.append(peopleArray)
    }
 }

 print(finalArray)

输出:

[["Jack", "Jones", "Rock", "Taylor", "Rob"], ["Rose", "John"], ["Ted"]]

在您的情况下,它将是:

if let path = Bundle.main.path(forResource: "People", ofType: "json") {
    let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [Any]

    var finalArray:[Any] = []

    for peopleDict in peoplesArray {
        if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
            finalArray.append(peopleArray)
        }
    }

    print(finalArray)
}

你在这里首先是一个包含 3 个对象的数组。 每个对象都是一个字典,其中键是人,值是一个字符串数组。 当您尝试进行 jsonserialization 时,您必须将其转换为预期结果。 所以你首先有一个对象数组,然后你有一个带有 String: Any 的字典,然后你获得一个 String 数组

let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as? [AnyObject]
guard let peoplesObject = peoplesArray["people"] as? [[String:Any]] else { return }
for people in peoplesObject {
    print("\(people)")
}

我无法将它粘贴到评论中,它太长或什么的

static func photosFromJSONObject(data: Data) -> photosResult {
    do {
        let jsonObject: Any =
                try JSONSerialization.jsonObject(with: data, options: [])

        print(jsonObject)

        guard let
              jsonDictionary = jsonObject as? [NSObject: Any] as NSDictionary?,
              let trackObject = jsonDictionary["track"] as? [String: Any],
              let album = trackObject["album"] as? [String: Any],
              let photosArray = album["image"] as? [[String: Any]]
                else {
            return .failure(lastFMError.invalidJSONData)
        }
    }
}

json 是这样的:

{
  artist: {
    name: Cher,
    track: {
        title: WhateverTitle,
        album: {
          title: AlbumWhatever,
          image: {
             small: "image.px",
             medium: "image.2px",
             large: "image.3px"}
       ....

假设 json 是编码数据

var arrayOfData : [String] = []
dispatch_async(dispatch_get_main_queue(),{
    for data in json as! [Dictionary<String,AnyObject>]
    {
        let data1 = data["People"]

        arrayOfData.append(data1!)
    }
})

您现在可以使用 arrayOfData。 :D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM