-1

我是 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

}   

}
4

2 回答 2

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 在这里有一些信息

于 2015-05-10T11:52:14.197 回答
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)
于 2015-05-10T07:00:47.750 回答