如何在Swift中解析数组JSON到数组

时间:2017-02-07 03:21:35

标签: ios arrays json 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" .."罗布"和第二个细胞有"玫瑰" ,"约翰"第三个细胞作为" Ted"

PLease帮助我了解如何实现这个目标

5 个答案:

答案 0 :(得分:10)

您可以利用Swift 4 Decodable

以优雅且安全的方式执行此操作

首先为人员阵列定义一种类型。

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"]

答案 1 :(得分:9)

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

答案 2 :(得分:1)

我无法在评论中粘贴它,它太长了或什么

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

答案 3 :(得分:0)

你在这里首先是一个包含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)") 
 }

答案 4 :(得分:0)

假设json是编码数据

Activity

您现在可以使用arrayOfData。 :d