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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42081141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:51:07  来源:igfitidea点击:

How to parse Array of JSON to array in Swift

iosarraysjsonswift

提问by Ashh

I'm trying to parse JSON which is like below

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

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

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

to an array which results in [ ["Hyman", "Jones", "Rock", "Taylor", "Rob"] , ["Rose", "John"], ["Ted"] ]

到一个数组,结果为 [ [["Hyman", "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 =     (
        Hyman,
        "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 "Hyman" .."Rob" and Second cell has "Rose" , "John" and third cell as "Ted"

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

PLease help me to understand how to achieve this

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

采纳答案by Bista

 var peoplesArray:[Any] = [
    [
        "People": [
        "Hyman",
        "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:

输出:

[["Hyman", "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)
}

回答by mokagio

You can do this in an elegant and type safe way leveraging Swift 4 Decodable

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

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.

然后 make it 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 { 
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) }
}
.names } // => ["Hyman", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]

回答by anckydocky

I couldn't pasted it in a comment, it is too long or something

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

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

And the json was something like:

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

回答by Gabriel M.

let assume that the json is the encoded data

假设 json 是编码数据

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

You can now use the arrayOfData. :D

您现在可以使用 arrayOfData。:D

回答by anckydocky

what you have here is first an array of 3 objects. 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. So you have first an array of objects, then you have a dictionary with String: Any, then you obtain an array of String

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

##代码##