如何解析 JSON 数组到阵列中Swift

标签: json ios Swift
发布时间: 2017/3/1 0:57:04
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试图解析 JSON 就像是下面

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

        ]
      },
      {
        "People": [
          "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"
    );
}
 .....

我很困惑如何解析时有"人"重复 3 次

试图在 UITableView 在那里我第一单元格有"杰克"中显示的内容......"罗布"和第二个单元格为"泰德"有"玫瑰"、"约翰"和三个单元格中

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

解决方法 1:

 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)
}
赞助商