swift 简单学习之数据解析

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
        })
    }

}

解析responseObject为模型

对于OC可以使用下面两种简便的方法.
  1. 使用NSObject的setValuesForKeysWithDictionary方法,但是这个不支持模型里面嵌套别的模型这种复杂的转换
  2. 使用MJExtension,这个可以支持模型的嵌套,非常强大,OC推荐使用.

这两种方法都可以自动将NSObject类型转换成OC的基本数据类型<br/>
但是在Swift中,只支持NSNumber,NSString(String)等继承自NSObject类型的数据类型,像Int,Double,Float这种基本数据类型无法做到自动转换.

我们只能通过构造方法将JSON对象解析成模型,这样更容易定制.

字典结构:
[
    "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() {

    }
}

图书模型:

 //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"
 }

解析代码:

 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 ?? ""
        }

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值