我是Swift和JSON的新手,所以如果这是愚蠢的话,请耐心等待。我试图在swift中解析这个特殊的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
}
}
答案 0 :(得分: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
答案 1 :(得分:0)
这是一个如何解析上面列出的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)