【发布时间】:2016-09-18 14:13:40
【问题描述】:
我想解析这个 JSON :http://jsonplaceholder.typicode.com/users 我在查找 JSON 结构时遇到问题。 我正在尝试使用这种结构良好的 JSON,但我不确定这是不是更好的方法! 解析此 JSON 数组以发布实例的最佳方法是什么? 有我的代码:
func profileFromJSONData(data : NSData) -> ProfileResult {
do{
let jsonObject : NSArray!
= try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSArray
for profileJSON in jsonObject {
if let profile = profileFromJsonObject(profileJSON as! NSDictionary) {
finalProfile.append(profile)
}
}
return .Success(finalProfile)
}
catch let error {
return .Failure(error)
}
}
func profileFromJsonObject(json: NSDictionary) -> UserProfile?{
guard let
id = json["id"] as? Int,
name = json["name"] as? String,
userName = json["username"] as? String,
email = json["email"] as? String,
address = json["address"] as? NSDictionary,
phone = json["phone"] as? String,
website = json["website"] as? String,
company = json["company"] as? NSDictionary
else {
return nil
}
let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company)
return obj
}
【问题讨论】: