如何从Json获得特定的价值?

我有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" } ] 

您可以检查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) } } } } } 

第一步:准备你的模型,如下面的代码片段所示。

 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:声明一个数组来存储parsing的地址。

 var addressesArray = [Addresses]() 

第三步:

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

就是这样,照顾数据types,你可以使用addressesArray来显示数据。