简体   繁体   English

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

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

I'm trying to parse JSON which is like below我正在尝试解析如下所示的 JSON

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

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

to an array which results in:到一个数组,结果是:

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

which is array of arrays.这是数组的数组。

I tried with code below我尝试使用下面的代码

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)
    }
}

when I print "people" I get o/p as当我打印“人”时,我得到 o/p 作为

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

I'm confused how to parse when it has "People" repeated 3 times当“People”重复 3 次时,我很困惑如何解析

Trying to display content in UITableView where my 1st cell has "Jack".."Rob" and Second cell has "Rose", "John" and third cell as "Ted"尝试在 UITableView 中显示内容,其中我的第一个单元格有“Jack”..“Rob”,第二个单元格有“Rose”、“John”,第三个单元格为“Ted”

PLease help me to understand how to achieve this请帮助我了解如何实现这一目标

You can do this in an elegant and type safe way leveraging Swift 4Decodable您可以利用 Swift 4Decodable以优雅且类型安全的方式执行此操作

First define a type for your people array.首先为您的 people 数组定义一个类型。

struct People {
  let names: [String]
}

Then make it Decodable , so that it can be initialised with a JSON.然后将其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)
  }
}

Now you can easily decode your JSON input现在您可以轻松解码您的 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
}

Finally to get get your linear array of names you can do最后得到你可以做的名字的线性数组

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)

output:输出:

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

In your case, it will be:在您的情况下,它将是:

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)
}

what you have here is first an array of 3 objects.你在这里首先是一个包含 3 个对象的数组。 each object is a dictionary where the key is people and the value is an array of strings.每个对象都是一个字典,其中键是人,值是一个字符串数组。 when you're trying to do jsonserialization, you have to cast it down to the expected result.当您尝试进行 jsonserialization 时,您必须将其转换为预期结果。 So you have first an array of objects, then you have a dictionary with String: Any, then you obtain an array of String所以你首先有一个对象数组,然后你有一个带有 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)")
}

I couldn't pasted it in a comment, it is too long or something我无法将它粘贴到评论中,它太长或什么的

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)
        }
    }
}

And the json was something like: json 是这样的:

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

let assume that the json is the encoded data假设 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!)
    }
})

You can now use the arrayOfData.您现在可以使用 arrayOfData。 :D :D

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

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