HandyJSON使用

HandyJSON使用

========================
我觉得看这代码就知道怎么用了,这个大都配合SwiftyJSON使用。

模型示例

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
28
29
30
31
32
33
34
35
36
37
import SwiftUI
import Foundation
import ObjectMapper
import Then
import RxSwift
import RxCocoa
import HandyJSON

struct Introduction: Identifiable, Decodable, Mappable, HandyJSON {
init() {
}
init?(map: Map) {
}
var id = UUID()
var idForDataBase: Int64 = Int64()
var image: String = String()
var title: String = String()
var text: String = String()
//这里的date原是想要展示日期,现在就用于当备注
var date: String = String()
init(idForDataBase: Int64, image: String, title: String, text: String, date: String) {
self.idForDataBase = idForDataBase
self.image = image
self.title = title
self.text = text
self.date = date
}
mutating func mapping(map: Map) {
id <- map["id"]
idForDataBase <- map["idForDataBase"]
image <- map["image"]
title <- map["title"]
text <- map["text"]
date <- map["date"]
}
}

//解析的话,只遵循HandyJSON协议即可,如下,这样就可以使用了:

1
2
3
4
5
6
7
8
9
10
import Foundation
import HandyJSON

struct Introduction: HandyJSON {
var idForDataBase = Int64()
var image: String = String()
var title: String = String()
var text: String = String()
var date: String = String()
}

使用示例

在合适的地方调用,这里主要是JSONDeserializer<Introduction>.deserializeModelArrayFrom(json: culturalRelicsData.description)使用了HandyJSON,不要太轻松。

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//
// NetworkTool.swift
// RunInto
//
// Created by 张赛东(手机:15674119605) on 2021/3/30.
// Copyright © 2021 adong666666. All rights reserved.
//
//swiftlint:disable void_return
import Foundation
import Alamofire
import SwiftyJSON
import HandyJSON

protocol NetworkToolProtocol {
static func loadCulturalRelicsData(input: IntroductionAPI, completionHandler: @escaping ([Introduction?]) -> ())
}

extension NetworkToolProtocol {
static func loadCulturalRelicsData(input: IntroductionAPI, completionHandler: @escaping ([Introduction?]) -> ()) {
// AF.request(culturalRelicsDataUrl, method: .get, parameters: [:]).responseJSON(completionHandler: { (response) in
// let value = response.value
// let json = JSON(value as Any)
// log(json)
// })
introductionPovider.request(input) { (result) in
if case let .success(response) = result {
//解析数据
let data = try? response.mapJSON()
let json = JSON(data!)
let culturalRelicsData = json["data"]["culturalRelicsData"]
//log(json)
//log(culturalRelicsData)
if let mappedObject = JSONDeserializer<Introduction>.deserializeModelArrayFrom(json: culturalRelicsData.description) {
//log(mappedObject)
//log(mappedObject.count)
completionHandler(mappedObject)
}
}
}
}
}

struct NetworkTool: NetworkToolProtocol {}