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

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

本文介绍了如何在Swift中解析数组JSON到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse JSON which is like below

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

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

一个数组导致[[杰克,琼斯,摇滚,泰勒,罗布],[玫瑰,约翰] ,[Ted]]

to an array which results in [ ["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)
            }

        }

当我打印people时,我得到o / p为

when I print "people" I get o/p as

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

我很困惑如何解析当它有People重复3次时

I'm confused how to parse when it has "People" repeated 3 times

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

Trying to display content in UITableView where my 1st cell has "Jack" .."Rob" and Second cell has "Rose" , "John" and third cell as "Ted"

PLease帮助我理解如何实现这个

PLease help me to understand how to achieve this

推荐答案

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

在你的情况下,它将是:

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

这篇关于如何在Swift中解析数组JSON到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:22