HandyJSON-数据解析

总结:

  • 前期配置了HadyJSON,然后再使用的时候,不用再写handyJSON的代码,直接使用就行,转换过as?之前定义的数据模型
  • 每次都给值附一个初始值
  • 继承HandyJSON的用法
    • 只要你定义好Model类,声明它服从HandyJSON协议,HandyJSON就能自行以各个属性的属性名为Key,从JSON串中解析值。
1
2
3
pod ‘HandyJSON'

import HandyJSON

HandyJSON支持 JSON直接转Model,定义class时,有两点注意:

  • 必须遵循HandyJSON协议
  • 需要实现空的initializer (当然Struct结构体 可以不需要init(),下文有说明)

  • 实现例子1—对class{驾驶证识别的时候就是返回这些数据,已经实践过,按照下面方法没问题,刘汶,还可以叠加模型}
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class BasicTypes: HandyJSON {
    var int: Int = 2
    var doubleOptional: Double?
    var stringImplicitlyUnwrapped: String!

    required init() {}
    }

    let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"

    if let object = BasicTypes.deserialize(from: jsonString) {
    // …
    }

实现例子2–支持Struct,使用方式与Class基本一致

  • 注意一下,虽然Struct自己已经帮助构造了init初始化,但如果我们需要重载init,构造我们自己的初始化,还是需要写一下的
1
2
3
4
5
6
7
8
9
10
11
struct BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
}

let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"

if let object = BasicTypes.deserialize(from: jsonString) {
// …
}

实现例子3—支持枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum AnimalType: String, HandyJSONEnum {
case Cat = "cat"
case Dog = "dog"
case Bird = "bird"
}

struct Animal: HandyJSON {
var name: String?
var type: AnimalType?
}

let jsonString = "{\"type\":\"cat\",\"name\":\"Tom\"}"
if let animal = Animal.deserialize(from: jsonString) {
print(animal.type?.rawValue)
}


实现例子4–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
class BasicTypes: HandyJSON {
var bool: Bool = true
var intOptional: Int?
var doubleImplicitlyUnwrapped: Double!
var anyObjectOptional: Any?

var arrayInt: Array<Int> = []
var arrayStringOptional: Array<String>?
var setInt: Set<Int>?
var dictAnyObject: Dictionary<String, Any> = [:]

var nsNumber = 2
var nsString: NSString?

required init() {}
}

let object = BasicTypes()
object.intOptional = 1
object.doubleImplicitlyUnwrapped = 1.1
object.anyObjectOptional = "StringValue"
object.arrayInt = [1, 2]
object.arrayStringOptional = ["a", "b"]
object.setInt = [1, 2]
object.dictAnyObject = ["key1": 1, "key2": "stringValue"]
object.nsNumber = 2
object.nsString = "nsStringValue"

let jsonString = object.toJSONString()!

if let object = JSONDeserializer<BasicTypes>.deserializeFrom(json: jsonString) {
// ...
}


实现例子5–HandyJSON支持指定从哪个具体路径开始解析,反序列化到Model。

  • 正常情况下,接口一般都会返回包括错误码,错误消息,正式请求数据等,但我们一般只需要把正式数据转换成Model即可。
  • 直接通过 designatedPath 定位到我们需要的节点处。
1
2
3
4
5
6
7
8
9
10
11
12
class Cat: HandyJSON {
var id: Int64!
var name: String!

required init() {}
}

let jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"

if let cat = JSONDeserializer<Cat>.deserializeFrom(json: jsonString, designatedPath: "data.cat") {
print(cat.name)
}

实现例子6–handyJSON支持有继承关系的Model类,就是说及时某个类没有实现HandyJSON协议,只要父类有实现,依然可以转化model。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Animal: HandyJSON {
var id: Int?
var color: String?

required init() {}
}


class Cat: Animal {
var name: String?

required init() {}
}

let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"

if let cat = JSONDeserializer<Cat>.deserializeFrom(json: jsonString) {
print(cat)
}


实现例子7:反过来–HandyJSON还支持对象转字典、对象转模型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!

required init() {}
}

let object = BasicTypes()
object.int = 1
object.doubleOptional = 1.1
object.stringImplicitlyUnwrapped = “hello"

print(object.toJSON()!) // 序列化到字典
print(object.toJSONString()!) // 序列化到JSON字符串
print(object.toJSONString(prettyPrint: true)!) // 序列化为格式化后的JSON字符串

实现例子8:与Alamofire结合使用

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
44
45
/// 结构体model 来接收得到的jsonString
struct responseModel: HandyJSON {

var data:[TagModel]?
var error: Int!
}
struct TagModel: HandyJSON {

var nickname: String?
var vertical_src: String?
var ranktype: String?
var room_src: String?
var cate_id: Int?
}
extension TestController {

fileprivate func getData() {

let recommend_collectionurl = "http://capi.douyucdn.cn/api/v1/getbigDataRoom?aid=ios&client_sys=ios&time=1468636740&token=30890623_1b036814902f6451&auth=7d7026a323e09dd55c71ca215fc9d4b2"

Alamofire.request(recommend_collectionurl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseString { (response) in

if response.result.isSuccess {

if let jsonString = response.result.value {

/// json转model
/// 写法一:responseModel.deserialize(from: jsonString)
/// 写法二:用JSONDeserializer<T>
if let responseModel = JSONDeserializer<responseModel>.deserializeFrom(json: jsonString) {

/// model转json 为了方便在控制台查看
print(responseModel.toJSONString(prettyPrint: true)!)

/// 遍历responseModel.data
responseModel.data?.forEach({ (model) in
print(model.nickname!);
})

}
}
}
}
}
}


实现例子9:序列化和反序列化

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
class TestModel: HandyJSON {

var age: Int?
var name: String!
var sex: String?

required init(){}
}
extension TestController {

/// 反序列化
fileprivate func test1() {

let jsonString = "{\"age\":24,\"name\":\"Micheal\",\"sex\":\"男\"}"
guard let model = TestModel.deserialize(from: jsonString) else {return}

print(model.name)/// Micheal
print(model.age!)/// 24
print(model.sex!)/// 男
}

/// 序列化
fileprivate func test2() {

let model = TestModel()
model.name = "Mike"
model.age = 24
model.sex = "男"

print(model.toJSON()!)/// 输出格式为 ["age": Optional(24), "name": Mike, "sex": Optional("男")]
print(model.toJSONString()!)/// 输出格式为 {"age":24,"name":"Mike","sex":"男"}
print(model.toJSONString(prettyPrint: true)!)
// 输出格式为
/*
{
"age" : 24,
"name" : "Mike",
"sex" : "男"
}
*/
}
}


实现例子10–映射

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
44
45
46
class Cat3: HandyJSON {

var id: Int64!
var name: String!
var parent: (String, String)? // 元祖类型

required init() {}

/// 实现一个可选的mapping函数,在里边实现NSString值(HandyJSON会把对应的JSON字段转
换为NSString)转换为你需要的字段类型

public func mapping(mapper: HelpingMapper) {

// 将json中的cat_id这个key 转换为id 属性

// 写法一
mapper <<< self.id <-- "cat_id"

// 写法二
mapper.specify(property: &id, name: "cat_id")

mapper <<<
self.parent <-- TransformOf<(String, String), String>.init(fromJSON: { (rawString) -> (String, String)? in
if let parentNames = rawString?.characters.split(separator: "/").map(String.init) {
return (parentNames[0], parentNames[1])
}
return nil
}, toJSON: { (tuple) -> String? in
if let _tuple = tuple {
return "\(_tuple.0)/\(_tuple.1)"
}
return nil
})
}
}
extension TestController {

fileprivate func test10() {

let jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\"}"
if let cat = Cat3.deserialize(from: jsonString) {
print(cat.id)
print(cat.parent!)
}
}
}


第二部分 使用issu

1
2
3
4
5
#if swift(>=4.1)
return NominalTypeDescriptor(pointer: relativePointer(base: base, offset: base.pointee - base.hashValue))
#else
return NominalTypeDescriptor(pointer: relativePointer(base: base, offset: base.pointee))
#endif


不错

参考