如何在iOS Swift中过滤JSON并获取值?



我正在尝试过滤JSON并获得键&值来解析它。这里所有的JSON值都是动态的。现在我需要找到"type = object"如果找到的类型为真,那么我需要检查value ={"contentType","URL" .

这是我的JSON:
{
"date": {
"type": "String",
"value": "03/04/1982",
"valueInfo": {}
},
"Scanner": {
"type": "Object",
"value": {
"contentType": "image/jpeg ",
"url": "https://www.pexels.com/photo/neon-advertisement-on-library-glass-wall-9832438/",
"fileName": "sample.jpeg"
},
"valueInfo": {
"objectTypeName": "com.google.gson.JsonObject",
"serializationDataFormat": "application/json"
}
},
"startedBy": {
"type": "String",
"value": "super",
"valueInfo": {}
},
"name": {
"type": "String",
"value": "kucoin",
"valueInfo": {}
},
"ScannerDetails": {
"type": "Json",
"value": {
"accountNumber": "ANRPM2537J",
"dob": "03/04/1982",
"fathersName": "VASUDEV MAHTO",
"name": "PRAMOD KUMAR MAHTO"
},
"valueInfo": {}
}
}

解码代码:

AF.request(v , method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseJSON { (response:AFDataResponse<Any>) in


print("process instance id api document view list::::",response.result)



switch response.result {
case .success:

let matchingUsers = response.value.flatMap { $0 }.flatMap { $0. == "object" }

print("new object doc:::", matchingUsers)

guard let data = response.value  else {
return
}


print("new object doc:::", matchingUsers)

if let newJSON = response.value {

let json = newJSON as? [String: [String:Any]]
print("new object doc:::", json as Any)

//                    let dictAsString = self.asString(jsonDictionary: json)

let vc = self.stringify(json: json ?? [])

print("dictAsString ::: dictAsString::::==",vc)

let data = vc.data(using: .utf8)!
do{
let output = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: [String:String]]
print ("demo:::==(String(describing: output))")
}
catch {
print (error)
}


do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String: [String:String]]
{
print("json array::::",jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}


}

self.view.removeLoading()

case .failure(let error):
print("Error:", error)
self.view.removeLoading()
}

}

如何从JSON中获得特定的值?如有任何帮助,不胜感激。

这是我的操场的代码与你的json样本:

import Foundation
let json = """
{
"date": {
"type": "String",
"value": "03/04/1982",
"valueInfo": {}
},
"Scanner": {
"type": "Object",
"value": {
"contentType": "image/jpeg ",
"url": "https://www.pexels.com/photo/neon-advertisement-on-library-glass-wall-9832438/",
"fileName": "sample.jpeg"
},
"valueInfo": {
"objectTypeName": "com.google.gson.JsonObject",
"serializationDataFormat": "application/json"
}
},
"startedBy": {
"type": "String",
"value": "super",
"valueInfo": {}
},
"name": {
"type": "String",
"value": "kucoin",
"valueInfo": {}
},
"ScannerDetails": {
"type": "Json",
"value": {
"accountNumber": "ANRPM2537J",
"dob": "03/04/1982",
"fathersName": "VASUDEV MAHTO",
"name": "PRAMOD KUMAR MAHTO"
},
"valueInfo": {}
}
}
"""
let data = json.data(using: .utf8, allowLossyConversion: false)!
struct ObjectScanner: Decodable {
let contentType: String
let url: String
let fileName: String
}
enum ObjectScannerType {
case object(ObjectScanner)
}
struct Scanner: Decodable {
enum ScannerType: String, Decodable {
case object = "Object"
}
enum CodingKeys: String, CodingKey {
case type, value
}
let scanner: ObjectScannerType
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(ScannerType.self, forKey: .type)
switch type {
case .object:
let value = try container.decode(ObjectScanner.self, forKey: .value)
scanner = .object(value)
}
}
}
struct DateResponse: Decodable {
let type: String
let value: String
// let valueInfo // Not enough information in sample for me to decode this object
}
struct Response: Decodable {
enum CodingKeys: String, CodingKey {
case date
case scanner = "Scanner"
}
let date: DateResponse
let scanner: Scanner
}
let decoder = JSONDecoder()
do {
let response = try decoder.decode(Response.self, from: data)
print(response)
} catch {
print("Error decoding: (error.localizedDescription)")
}

注意:这个例子是非常不可原谅的。任何不支持的缺失值或类型都将导致DecodingError。由您来决定所有可能的类型,以及哪些是可选的,哪些不是。

我也没有解码一切,也没有处理date对象到它的全部

这是一个非常复杂的例子。其中的一切都是多态的:dateScannerScannerDetails等等。你需要非常小心你如何解码,并确保你处理所有的可能性。如果你刚开始学习,我建议你应该探索更简单的例子。

我也选择使用枚举。不是每个人都会选择,但这是我的首选解码多态类型,如这些。

您可以在这里阅读我关于处理多态类型以及未知类型的文章:https://medium.com/@jacob.sikorski/awesome-use-swift-enums-2ff011a3b5a5

最新更新