簡體   English   中英

如何在 Swift 中將 JSON 數組解析為數組

[英]How to parse Array of JSON to array in 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”..“Rob”,第二個單元格有“Rose”、“John”,第三個單元格為“Ted”

請幫助我了解如何實現這一目標

您可以利用 Swift 4Decodable以優雅且類型安全的方式執行此操作

首先為您的 people 數組定義一個類型。

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

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

我無法將它粘貼到評論中,它太長或什么的

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

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

您現在可以使用 arrayOfData。 :D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM