0%

swift中从json转object

前言

本文列举了从网络请求和本地文件两种 JSON 转 object 的方式

准备

第三方库

SwiftyJSON
ObjectMapper

定义Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class News: Mappable {

var id: String!
var lock: Bool!
var name: String!
var show: Bool!
var type: String!

required init?(map: Map) {

}

func mapping(map: Map) {
id <- map["id"]
lock <- map["lock"]
name <- map["name"]
show <- map["show"]
type <- map["type"]
}

}
一、本地 initialData.json 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"newsMenuVoList": [
{
"id": "news_all",
"lock": true,
"name": "热搜",
"show": true,
"type": "推荐"
},
{
"id": "news_1",
"lock": false,
"name": "国际",
"show": true,
"type": "推荐"
}
]
1.读取本地文件转化成Dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func queryInitialDic() -> Any {

if self.initialDic == nil {

let path = Bundle.main.path(forResource: "initialData", ofType: "json")
let data = NSData.init(contentsOfFile: path!)

var dic: Any?

do {
dic = try JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments)

self.initialDic = dic!

return dic!
} catch {

}

} else {
return self.initialDic
}

return NSNull()
}
2.转Object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class NewsManager: NSObject {

static let sharedInstance = NewsManager()

var newsArray = [News]()

override init() {
super.init()

let array = NewsInitializer.sharedInstance.newsMenuVoList()
var tempArray = [News]()

for (_, value) in array.enumerated() {
let json = JSON(value)
if let jsongString = json.rawString() {
if let news = News(JSONString: jsongString) {
tempArray.append(news)
}
}
}
}
}
二、读取接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func fetchNews(withID id: String, page: Int, completionHandler:@escaping (Array<News>?) -> ()){

var tempArray = [News]()

let paras = [ "id": id,
"page": page ] as [String : Any]

Alamofire.request(NEWS_API, parameters: paras).responseJSON { response in

if let data: Dictionary = response.result.value as? Dictionary<String, Any> {

let arr: Array<Any> = data["list"] as! Array<Any>
for (_ , value) in arr.enumerated() {
let json = JSON(value)
if let jsongString = json.rawString() {
if let news = News(JSONString: jsongString) {
tempArray.append(news)
}
}
}
completionHandler(tempArray)
} else {
completionHandler(nil)
}
}

}