如何快速解析这个特定的 json
Posted
技术标签:
【中文标题】如何快速解析这个特定的 json【英文标题】:how to parse this particular json in swift 【发布时间】:2015-05-10 05:56:18 【问题描述】:我是 Swift 和 JSON 的新手,所以如果这很愚蠢,请多多包涵。我正在尝试快速解析这个特定的 JSON http://jsonplaceholder.typicode.com/users。我可以通过键入 http://jsonplaceholder.typicode.com/users/1 来获取一位用户的值,但问题是,它一次只为我提供一位用户的值。我正在寻找一种方法来一次性获取所有用户的价值。
我正在使用 SwiftyJSON API。
这是我一直在使用的代码:
// RestApiManager.swift
import Foundation
typealias ServiceResponse = (JSON, NSError?) -> Void
class RestApiManager: NSObject
static let sharedInstance = RestApiManager()
let baseURL = "http://jsonplaceholder.typicode.com/users/"
func getUser(onCompletion: (JSON) ->Void)
makeHTTPGetRequest(baseURL, onCompletion: json, err -> Void in onCompletion(json))
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse)
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: data, response, error in
let json:JSON = JSON(data: data)
onCompletion(json, error)
)
task.resume()
这是我的 MasterViewController.swift 类
//
// MasterViewController.swift
//
//
import UIKit
class MasterViewController: UITableViewController
var objects = [AnyObject]()
var contactsData = NSMutableArray() //array that will hold all the contact details.
override func awakeFromNib()
super.awakeFromNib()
override func viewDidLoad()
super.viewDidLoad()
getContactListJSON()
func getContactListJSON()
RestApiManager.sharedInstance.getUser json -> Void in
let user: AnyObject = json["id"].object
self.contactsData.addObject(user)
println(self.contactsData)
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
return 1
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return contactsData.count
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
var cell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as? UITableViewCell
return cell
【问题讨论】:
【参考方案1】:其实很简单。只需执行以下操作即可:
func getContactListJSON()
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) (data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(),
for contacts in contactsArray
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
)
task.resume()
我怀疑 swiftyJSON 有一些信息 here
【讨论】:
PS 如果 "id" 总是一个 int 你也可以这样做:let id = contacts["id"].intValue 非常感谢!它工作得很好!我心中还有一个问题,如果 let's id 为 nil 会发生什么? 嗨。然后该值将为零。您实际上应该执行以下操作: var id:String? if let id = contacts["id"].stringValue //do something with id else do something else or nothing 如果您认为答案是正确的,请将我的帖子标记为答案并投票给任何一个。非常感谢 我是 swift 和 JSON 的新手,当我尝试用这些值填充表时遇到了一些错误。你能帮我解决这个问题吗?谢谢! 没关系,我想通了。感谢您的帮助!【参考方案2】:这里是如何解析上面列出的 json 数组的简单实现。请注意,这并不能正确检查 json 值为 nil 的所有情况。因此,请使用可选检查以确保它不会崩溃。
class Geolocation
var latitude: String!
var longitude: String!
class Company: Printable
var name: String!
var bs: String!
var catchPhrase: String!
var description: String
get
return "\(name), catchPhrase: \(catchPhrase)"
class Address: Printable
var description: String
return "City: \(city), Street: \(street), suite: \(suite), zipCode: \(zipCode), geocode: \(geocode)"
var city: String!
var street: String!
var suite: String!
var zipCode: String!
var geocode: Geolocation!
class Person: Printable
var description: String
get
return "identifier: \(identifier) name:\(name) email:\(email) phone:\(phone) username:\(userName) website:\(website)\n Company: \(company), Address: \(address)"
var identifier: Int!
var name: String!
var email: String!
var phone: String!
var userName: String!
var website: String!
var company: Company!
var address: Address!
func createCompany(companyDict: NSDictionary) -> Company
let company = Company()
company.name = companyDict["name"] as! String
company.catchPhrase = companyDict["catchPhrase"] as! String
company.bs = companyDict["bs"] as! String
return company
func createGeolocation(geoDict: NSDictionary) -> Geolocation
let geo = Geolocation()
geo.latitude = geoDict["lat"] as? String
geo.longitude = geoDict["lng"] as? String
return geo
func createAddress(addressDict: NSDictionary) -> Address
let address = Address()
address.street = addressDict["street"] as? String
address.suite = addressDict["suite"] as? String
address.city = addressDict["city"] as? String
address.zipCode = addressDict["zipCode"] as? String
address.geocode = createGeolocation(addressDict["geo"] as! NSDictionary)
return address
func createPerson(personDict: NSDictionary) -> Person
let person = Person()
if let identifier = personDict["id"] as? Int
person.identifier = identifier
if let name = personDict["name"] as? String
person.name = name
if let email = personDict["email"] as? String
person.email = email
if let phone = personDict["phone"] as? String
person.phone = phone
if let username = personDict["username"] as? String
person.userName = username
if let website = personDict["website"] as? String
person.website = website
person.company = createCompany(personDict["company"] as! NSDictionary)
person.address = createAddress(personDict["address"] as! NSDictionary)
return person
let data = NSData(contentsOfFile: "/Users/Jackson/Desktop/MyPlayground.playground/Resources/test.json")
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: .allZeros, error: nil)
var personArray = [Person]()
for dict in json as! NSArray
if let personDict = dict as? NSDictionary
personArray += [createPerson(personDict)]
println(personArray)
【讨论】:
非常感谢您的帮助!但是通过这个实现,我们将不得不检查 json 值为 nil 的所有情况。有没有办法用我正在使用的代码完成它? 不用创建模型person,只需使用相同的NSArray来填充tableview,应该很简单。 我的意思是有没有使用 SwiftyJSON 的方法?以上是关于如何快速解析这个特定的 json的主要内容,如果未能解决你的问题,请参考以下文章