我正在使用如下所示的Json数据我需要获取哪个键值对默认为1的数据然后我需要获取剩余的词典数据并需要传递给用户才能显示任何一个告诉我如何实现这个?
我的代码如下所示
if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
for array in addressArray {
if let addressDict = array as? NSDictionary{
if let Default = addressDict.value(forKey: "default"){
}
}
}
}
"address": [
{
"default": 0,
"number": 9123456711,
"name": "Ramesh",
"address": "No:11/111 ,cross street,Nungambakkam,mylapore,chennai :600088"
},
{
"default": 1,
"number": 8123456722,
"name": "Vignesh",
"address": "No:22/222 ,cross street,Perambur,chennai :600012"
},
{
"default": 0,
"number": 7123456733,
"name": "Rajesh",
"address": "No:33/333 ,cross street,Villivakkam,chennai :600045"
}
]
答案 0 :(得分:0)
您可以检查Default是否等于1并将这些值添加到数组中。
var defaultArray = [NSDictionary]()
if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
for array in addressArray {
if let addressDict = array as? NSDictionary{
if let Default = addressDict.value(forKey: "default"){
if Default == 1 {
defaultArray.append(addressDict)
}
}
}
}
}
答案 1 :(得分:0)
步骤1:准备您的模型,如下面的代码段所示。
class Addresses: NSObject {
var default = 0
var number = 0
var name = String()
var address = String()
init?(dictionary:[String:Any]) {
guard let default = dictionary["default"],
let number = dictionary["number"],
let name = dictionary["name"],
let address = dictionary["address"]
else {
return nil
}
self.default = default
self.number = number
self.name = name
self.address = address
}
}
步骤2:声明一个数组来存储已解析的地址。
var addressesArray = [Addresses]()
第3步:
if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
for array in addressArray {
if let addressDict = array as? NSDictionary{
if let defaultValue = addressDict.value(forKey: "default") as? Int{
if defaultValue == 1 {
if let address = Addresses(dictionary: addressDict) {
addressesArray.append(address)
}
}
}
}
}
}
多数,它可以使用addressesArray来显示数据。