(一)获取数据
import UIKit
func printJSONObject(anyObject:AnyObject?) {
if let anyObject = anyObject,let data = try? NSJSONSerialization.dataWithJSONObject(anyObject, options: .PrettyPrinted) {
print(NSString(data: data, encoding: NSUTF8StringEncoding)!)
}
}
class BookViewController: UIViewController {
let searchPath = "https://api.douban.com/v2/book/search" //搜索图书URLString
var tag = "Swift" //搜索关键字
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
GET(searchPath, parameters: ["tag":tag,"start":0,"count":10,"field":"id,title,image,rating,author,publisher,pubdate"], showHUD:true, success: { (responseObject) -> Void in
printJSONObject(responseObject)
}, failure: {error in
})
}
}
parameters
可以看到0,10这样的Int,Swift会自动将其转换成NSNumber类型.
print默认会以Unicode格式打印Dictionary和Array,所以在printJSONObject将JSON对象转换成UTF8 NSString字符串打印,这样在控制台能输出很好的格式.
(二)解析responseObject为模型
对于OC可以使用下面两种简便的方法.
- 使用NSObject的setValuesForKeysWithDictionary方法,但是这个不支持模型里面嵌套别的模型这种复杂的转换
- 使用MJExtension,这个可以支持模型的嵌套,非常强大,OC推荐使用.
这两种方法都可以自动将NSObject类型转换成OC的基本数据类型
但是在Swift中,只支持NSNumber,NSString(String)等继承自NSObject类型的数据类型,像Int,Double,Float这种基本数据类型无法做到自动转换.
我们只能通过构造方法将JSON对象解析成模型,这样更容易定制.
图书信息主要涉及两个模型
1.评分
Dictionary结构
[
"min" : 0,
"max" : 10,
"numRaters" : 109,
"average" : "8.4"
]
解析代码
import UIKit
//评分
class Rating: NSObject {
var min:CGFloat = 0.0
var max:CGFloat = 0.0
var numRaters = 0 //评价数
var average:CGFloat = 0.0
init(dict:[String:AnyObject]) {
min = dict["min"] as? CGFloat ?? 0
max = dict["max"] as? CGFloat ?? 0
numRaters = dict["numRaters"] as? Int ?? 0
if let average = dict["average"]?.floatValue {
self.average = CGFloat(average * 5) / max
}
}
override init() {
}
}
给模型每个值都设个默认值,这样减少nil导致的崩溃
??表示如果转换失败了就会等于后面的默认值.
因为服务器人员的大意,可以看到average在字典中其实是String类型,而不像前面三者一样是NSNumber,所以并不能直接转换成CGFloat,而是需要使用NSValue的方法floatValue,豆瓣的评分最大是10,而我们app显示最大的是5,所以转换一下.
-
图书模型
//Dictionary结构 { "author" : [ "苹果公司" ], "translator" : [ ], "url" : "http:\/\/api.douban.com\/v2\/book\/25899841", "alt" : "http:\/\/book.douban.com\/subject\/25899841\/", "publisher" : "Apple Inc.", "images" : { "large" : "https:\/\/img3.doubanio.com\/lpic\/s27296746.jpg", "small" : "https:\/\/img3.doubanio.com\/spic\/s27296746.jpg", "medium" : "https:\/\/img3.doubanio.com\/mpic\/s27296746.jpg" }, "catalog" : "", "binding" : "电子书", "origin_title" : "", "rating" : { "min" : 0, "max" : 10, "numRaters" : 109, "average" : "8.4" }, "id" : "25899841", "pages" : "", "price" : "免费", "isbn13" : "9780300164695", "alt_title" : "", "author_intro" : "", "title" : "The Swift Programming Language", "summary" : "Swift is a new programming language for creating iOS and OS X apps. Swift builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works.\nThis book provides:\n- A tour of the language.\n- A detailed guide delving into each language feature.\n- A formal reference for the language.", "subtitle" : "Swift编程语言手册", "pubdate" : "2014-6-2", "isbn10" : "0300164696", "tags" : [ { "count" : 72, "name" : "iOS", "title" : "iOS" }, { "count" : 46, "name" : "Swift", "title" : "Swift" }, { "count" : 45, "name" : "编程", "title" : "编程" }, { "count" : 30, "name" : "计算机", "title" : "计算机" }, { "count" : 22, "name" : "swift", "title" : "swift" }, { "count" : 19, "name" : "程序设计", "title" : "程序设计" }, { "count" : 12, "name" : "技术", "title" : "技术" }, { "count" : 9, "name" : "软件开发", "title" : "件开发", "title" : "\350\275软件开发" } ], "image" : "https:\/\/img3.doubanio.com\/mpic\/s27296746.jpg" }
这是responseObject中每一本书的Dictionary结构,可以看到里面有个rating字段对应就是上面的评分模型
//解析代码
import UIKit
//图书信息
class Book: NSObject {
var id = ""
var isbn10 = "" //老的10位图书编码
var isbn13 = "" //新标准的13位编码
var title = ""
var origin_title = ""
var alt_title = ""
var subtitle = ""
var url = "" //json格式,图书详细信息
var alt = "" //html格式,图书详细信息
var image = ""
var images = [String:String]() //key:small、large、medium 对应三种质量的封面图
var author = [String]() //作者姓名
var translator = [String]() //译者姓名
var publisher = "" //出版社
var pubdate = ""
var rating = Rating()//图书评分信息
var tags = [[String:AnyObject]]() // 标签列表,key:count、name
var binding = "" //平装 精装
var price = ""
var series = [String:String]() //key:id、title
var pages = "" //总页数
var author_intro = ""
var summary = "" //摘要
var catalog = "" //序言
var ebook_url = "" //该字段只在存在对应电子书时提供
var ebook_price = ""
init(dict: [String : AnyObject]) {
id = dict["id"] as? String ?? ""
isbn10 = dict["isbn10"] as? String ?? ""
isbn13 = dict["isbn13"] as? String ?? ""
title = dict["title"] as? String ?? ""
origin_title = dict["origin_title"] as? String ?? ""
alt_title = dict["alt_title"] as? String ?? ""
subtitle = dict["subtitle"] as? String ?? ""
url = dict["url"] as? String ?? ""
alt = dict["alt"] as? String ?? ""
image = dict["image"] as? String ?? ""
images = dict["images"] as? [String:String] ?? [:]
author = dict["author"] as? [String] ?? []
translator = dict["translator"] as? [String] ?? []
publisher = dict["publisher"] as? String ?? ""
pubdate = dict["pubdate"] as? String ?? ""
if let ratingDict = dict["rating"] as? [String:AnyObject] {
rating = Rating(dict:ratingDict)
}
tags = dict["tags"] as? [[String:AnyObject]] ?? []
binding = dict["binding"] as? String ?? ""
price = dict["price"] as? String ?? ""
series = dict["series"] as? [String:String] ?? [:]
price = dict["price"] as? String ?? ""
pages = dict["pages"] as? String ?? ""
author_intro = dict["author_intro"] as? String ?? ""
summary = dict["summary"] as? String ?? ""
catalog = dict["catalog"] as? String ?? ""
ebook_url = dict["ebook_url"] as? String ?? ""
ebook_price = dict["ebook_price"] as? String ?? ""
}
}
在Controller中添加属性
var books = [Book]()
在printJSONObject(responseObject)后面添加
guard let dict = responseObject as? [String:AnyObject] else {
return
}
guard let array = dict["books"] as? [[String:AnyObject]] else {
return
}
for dict in array {
self.books.append(Book(dict: dict))
}
这样数据解析完毕了