您好我是swift语言的初学者,在我的项目中,我使用的是Web服务,在得到响应之后如何解析以下对Swift对象的响应可以帮助我一些
[
{
"id" : 1,
"first_name": "John",
"last_name": "Smith",
"age": 25,
"address": {
"id": 1,
"street_address": "2nd Street",
"city": "Bakersfield",
"state": "CA",
"postal_code": 93309
}
}
]
class Address:NSObject{
struct Address {
let objID: Int?
let streetAddress: String?
let city: String?
let state: String?
let postalCode: String?
}
struct User {
let objID: Int?
let firstName: String?
let lastName: String?
let age: Int?
let address : Address?
}
}
func finalResponse(response : AnyObject){
let addressArray = response as! NSArray;
for items in addressArray{
}
}
答案 0 :(得分:0)
在swift 4中,它变得更容易
您的模型类看起来像这样 键应与json响应相同或使用enum更改名称
struct Address: Decodable {
let objID: Int?
let streetAddress: String?
let city: String?
let state: String?
let postalCode: String?
}
struct User: Decodable {
let objID: Int?
let firstName: String?
let lastName: String?
let age: Int?
let address : Address?
}
}
您的视图Controller类看起来像这样
try decoder.decode([User.self], from: jsonData)
答案 1 :(得分:0)
这是objective-c swift 1,2,3
中的旧日方法这是模型类
class SafeJson: NSObject{
override func setValue(_ value: Any?, forKey key: String) {
let firstCharacter = String(key.characters.first!).uppercased()
let range = NSMakeRange(0,1)
let valuex = NSString(string: key).replacingCharacters(in: range, with: firstCharacter)
// let valuex = key.replacingCharacters(in: range, offsetBy: 0), with: firstCharacter)
let selector = NSSelectorFromString("set\(valuex):")
let respond = self.responds(to: selector)
if !respond{
return
}
super.setValue(value, forKey: key)
}
}
class Model:SafeJson{
// var thumbnail_image_name: String?
var title: String?
var number_of_views: NSNumber?
var channel: Channel?
override func setValue(_ value: Any?, forKey key: String) {
if key == "channel"{
self.channel = Channel()
let dictionary = value as! [String: AnyObject]
self.channel?.setValuesForKeys(dictionary)
}else{
super.setValue(value, forKey: key)
}
}
init(dictionary: [String: AnyObject]) {
super.init()
setValuesForKeys(dictionary)
}
}
class Channel:SafeJson{
var name: String?
var profile_image_name: String?
}
在您的View控制器类中您必须将响应传递给Model.init 它会自动保存到模型
但是在swift 4中,setValueForKey被删除 你必须使用可解码
答案 2 :(得分:0)
警告,没有测试它,所以让我知道任何警告,并将调整
对于Swift3
func finalResponse(response : AnyObject){
var result: [Address] = []
let json = response as! [String:AnyObject]
// ITERATE THROUGH THE ARRAY OF DICTIONARIES
for item in json {
// a WILL BE THE MAIN OBJECT YOU'RE CREATING
var a = Adress()
a.objID = item["id"] as! Int
.....
// REPEAT FOR EVERY ELEMENT UNTIL YOU REACH NEXT SUBCLASS
.....
// CREATE A NEW DICTIONARY FOR THE SUBCLASS Address
var b = item["address"] as! Dictionary<String, String>
a.address.objID = b["id"] as! Int
// IF YOU DON'T WANT TO CREATE var b YOU CAN WRITE
// a.address.objID = a["address"]["id"] INSTEAD
// ADD YOUR OBJECT TO RESULT
result.append(a)
}
}
答案 3 :(得分:0)
Herr是解析JSON数据中数据的代码。在我在代码中注释的位置创建结构。
do{
let json = try JSONSerialization.jsonObject(with: yourJSONData!, options: []) as? [Any]
let firstUser = json?[0] as? [String: Any]
let id = firstUser?["id"] as? Int
let firstName = firstUser?["first_name"] as? String
//etc... for other keys
let address = firstUser?["address"] as? [String, Any]
let streetAddress = address?["street_address"] as? String
let state = address?["state"] as? String
//etc... create your address struct here and then create the user struct
dump(firstPerson?["lastName"])
}catch let error{
}