我无法解决下一个问题。我从JSON获得具有相同键和不同值的Dictionary数组。 例如:
{
"data": [{
"name": "Anna",
"features": {
"age": "18",
"hobby": "football"
}
}, {
"name": "Peter",
"data": {
"age": "16",
"hobby": "computer games"
}
}, {
"name": "Peter",
"data": {
"age": "25",
"hobby": "chess",
"job": "fireman"
}
}
],
"view": ["Peter", "Anna", "Peter"]
}
这是我的解码结构:
struct Object: Decodable {
let objectData: [DictionaryData]
let bjectView: [String]
}
struct DictionaryData: Decodable {
let name: String
let features: Features?
let data: DataClass?
}
struct DataContainer: Decodable {
let age, hobby: String
let job: String?
}
struct Features: Decodable {
let age, hobby: String
}
这是我坚持的重点。我使用过滤器,但是当我需要字典值时它会返回布尔值:
var items = [ModelItem]()
var singleObject: Object!
func jsonParsing(completionHandler: @escaping (([ModelItem], Error?) -> Void)) {
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { DispatchQueue.main.async {completionHandler([], error)}
return
}
do {
self.singleObject = try JSONDecoder().decode(Object.self, from: data)
let sequenceArray = self.singleObject.objectView
for i in sequenceArray {
if i == "Peter" {
if let objectName = self.singleObject?.objectData.filter({ return $0.name == "Peter"}) ... {
let firstItem = ModelFirstItem(text: ...) //here should be a value
self.items.append(firstItem)
}
}
else if i == "Anna" {
...
}
}
}
DispatchQueue.main.async {completionHandler(self.items, nil)}
} catch {
print("Error serializing json:", error)
}
} .resume()
}
我如何获得年龄,爱好和工作价值? 谢谢!
答案 0 :(得分:0)
if let json = object as? [String: Any],
let dataJSON = json["data"] as? [[String: Any]] { //in the data field you have an array of dictionaries, maybe this is what you're stuck on?
dataJSON.forEach { jsonElement in
if let name = jsonElement["name"] as? String, name == "Peter" {
print(jsonElement["data"])
}
}
}
答案 1 :(得分:0)
JSON的可编码模型
struct Welcome: Codable {
let data: [Datum]
let view: [String]
}
struct Datum: Codable {
let name: String
let features: Feature?
let data: Data?
}
struct Data: Codable {
let age, hobby: String
let job: String?
}
struct Feature: Codable {let age, hobby: String}
解码JSON
let decoder = JSONDecoder()
let decodedObject = try! decoder.decode(Welcome.self, from: JSON)
let filterdPeter = decodedObject.data.filter {$0.name == "Peter"}.map({$0.data})
filterdPeter.forEach {print($0)}