在Swift中嵌套JSON到Array

时间:2022-05-05 00:54:11

There are already posts talking about this, but I am still not able to figure out my problem.

已有帖子谈论这个,但我仍然无法弄清楚我的问题。

I am accessing my database and am converting the response into a JSON object - that part is working fine. Here is the code for that. joArray now has the data I need.

我正在访问我的数据库,并将响应转换为JSON对象 - 该部分工作正常。这是代码。 joArray现在拥有我需要的数据。

//Convert data to json object
let joArray : NSArray
do {
    joArray = try JSONSerialization.jsonObject(with: data, options: []) as! NSArray
}
catch  {
    print(responseString)
    print("error trying to convert data to JSON")
    return
 }

If I print out joArray . . .

如果我打印出joArray。 。 。

print(joArray)

. . . this is what I get.

。 。 。这就是我得到的。

(
        {
        FirstName = Bob;
    },
        {
        FirstName = Bill;
    }
)

How can I put this data into a swift array so that it looks like this?

如何将这些数据放入一个快速数组中,使它看起来像这样?

let FirstNameArray = ["Bob", "Bill"]

FirstName will always be in the same position, but there will be varying numbers of users (Bob, Bill, Mary, etc.).

FirstName将始终处于相同的位置,但会有不同数量的用户(Bob,Bill,Mary等)。

1 个解决方案

#1


2  

You will make life easier for yourself if you use a native Swift array instead. So, start by changing your array definition:

如果您使用原生Swift数组,您将使自己的生活更轻松。因此,首先要更改数组定义:

let joArray: [[String: Any]]
do {
  joArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
} catch {
  // etc...
}

Now, it's straightforward to construct the required array:

现在,构建所需的数组非常简单:

let FirstNameArray = swiftArray.flatMap { $0["FirstName"] }

You should use flatMap, rather than map, because the given array item might not have a property called "FirstName".

您应该使用flatMap而不是map,因为给定的数组项可能没有名为“FirstName”的属性。

#1


2  

You will make life easier for yourself if you use a native Swift array instead. So, start by changing your array definition:

如果您使用原生Swift数组,您将使自己的生活更轻松。因此,首先要更改数组定义:

let joArray: [[String: Any]]
do {
  joArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
} catch {
  // etc...
}

Now, it's straightforward to construct the required array:

现在,构建所需的数组非常简单:

let FirstNameArray = swiftArray.flatMap { $0["FirstName"] }

You should use flatMap, rather than map, because the given array item might not have a property called "FirstName".

您应该使用flatMap而不是map,因为给定的数组项可能没有名为“FirstName”的属性。