JSON数据的初始化

31. January 2016 笔记 0

先通过访问json数据请求的地址,获得需要的字段,然后对其数据进行初始化。

import UIKit

struct Book { //swift官方更建议使用结构体

let KeyId = “id” //先对需要的参数名进行赋值操作,方便以后修改

let KeyIsbn10 = “isbn10”

let KeyIsbn13 = “isbn13”

let KeyTitle = “title”

let KeyOrigin_title = “origin_title”

let KeyAlt_title = “alt_title”

let KeySubtitle = “subtitle”

let KeyUrl = “url”

let KeyAlt = “alt”

let KeyImage = “image”

let KeyImages = “images”

let KeyAuthor = “author”

let KeyTranslator = “translator”

let KeyPublisher = “publisher”

let KeyPubdate = “pubdate”

let KeyRating = “rating”

let KeyTags = “tags”

let KeyBinding = “binding”

let KeyPrice = “price”

let KeySeries = “series”

let KeyPages = “pages”

let KeyAuthor_info = “author_info”

let KeySummary = “summary”

let KeyCatalog = “catalog”

let KeyEbook_url = “ebook_url”

let KeyEbook_price = “ebook_price”

var id = “” //对参数进行定义和初始化操作,初始值为空字符串

var isbn10 = “”

var isbn13 = “”

var title = “”

var origin_title = “”

var alt_title = “”

var subtitle = “”

var url = “”

var alt = “”

var image = “”

var iamges = [String:String]() //根据参数类型不同进行定义

var author = [String]()

var translator = [String]()

var publisher = “”

var pubdate = “”

var rating = “”

var tags = [[String:NSObject]]()

var binding = “”

var price = “”

var series = [String:NSObject]()

var pages = “”

var author_info = “”

var summary = “”

var catalog = “”

var ebook_url = “”

var ebook_price = “”

init(dict:[String:NSObject]){ //使用构造函数对参数进行初始化赋值,使用可选链,保证不会出现nil错误

id = dict[KeyId] as? String ?? “”

isbn10 = dict[KeyIsbn10] as? String ?? “”

isbn13 = dict[KeyIsbn13] as? String ?? “”

title = dict[KeyTitle] as? String ?? “”

origin_title = dict[KeyOrigin_title] as? String ?? “”

alt_title = dict[KeyAlt_title] as? String ?? “”

subtitle = dict[KeySubtitle] as? String ?? “”

url = dict[KeyUrl] as? String ?? “”

alt = dict[KeyAlt] as? String ?? “”

image = dict[KeyImage] as? String ?? “”

iamges = dict[KeyImages] as? [String:String] ?? [:]

author = dict[KeyAuthor] as? [String] ?? []

translator = dict[KeyTranslator] as? [String] ?? []

publisher = dict[KeyPublisher] as? String ?? “”

pubdate = dict[KeyPubdate] as? String ?? “”

rating = dict[KeyRating] as? String ?? “”

tags = dict[KeyTags] as? [[String:NSObject]] ?? []

binding = dict[KeyBinding] as? String ?? “”

price = dict[KeyPrice] as? String ?? “”

series = dict[KeySeries] as? [String:NSObject] ?? [:]

pages = dict[KeyPages] as? String ?? “”

author_info = dict[KeyAuthor_info] as? String ?? “”

summary = dict[KeySummary] as? String ?? “”

catalog = dict[KeyCatalog] as? String ?? “”

ebook_url = dict[ebook_url] as? String ?? “”

ebook_price = dict[ebook_price] as? String ?? “”

}

}


Leave a Reply

Your email address will not be published. Required fields are marked *