自定义组件封装之-如何使用SwfityJSON实现JSON/Model相互转换

最近在学习Swift的各种框架,在我的另一篇Swift框架学习之-数据解析SwiftyJSON,已经介绍过了如何使用SwfityJSON这个牛逼的纯Swift写的框架,这里就不作过多介绍,主要来说说我在SwiftyJSON基础之上封装的一个SwiftyJSONMappable框架:

我们以这个Json 数据为例:

 [
  {
  "id":17445752,
  "name":"王老师",
  "title":"副教授",
  "schoolAge":"15年",
  "homePage":"http://www.baidu.com",
  "description": "王老师从事大学教师职业15年,对于应用专业有很深的理解",
  "courses":[
            {
             "name": "应用英语",
             "time": "2017-06-17 10:00:00",
             "description": "王老师教学"
            },
             {
             "name": "应用数学",
             "time": "2017-06-18 10:00:00",
             "description": "王老师教学"
             }
            ]
  },
  {
  "id":17445753,
  "name":"杨老师",
  "title":"高级讲师",
  "schoolAge":"10年",
  "homePage":"http://www.baidu.com",
  "description": "杨老师从事大学教师职业10年",
  "courses":[
             {
             "name": "政治",
             "time": "2017-06-12 10:00:00",
             "description": "杨老师教学"
             },
             {
             "name": "密码学",
             "time": "2017-06-14 10:00:00",
             "description": "杨老师教学"
             }
             ]
  }
]

Installation(引用)

你可以通过cocoapod方式将其引入到你的工程

pod 'SwiftyJSONMappable'

Usage(用法)

  • 定义一个Model, 你需要实现JSONMappable协议
class Teacher: JSONMappable {
    var id: UInt
    var name: String
    var title: String
    var schoolAge: String
    var homePage: URL?
    var courses: [Course]?

    required init(json: JSON) {

        id = json["id"].uIntValue
        name = json["name"].stringValue
        title = json["title"].stringValue
        schoolAge = json["schoolAge"].stringValue
        homePage = URL(string: json["homePage"].stringValue)
        courses = json["courses"].arrayValue.map({ (json) -> Course in
            Course(json: json)
        })
    }
}
  • 将Model 转换为JSON
class Teacher: JSONMappable {
    // 此处省略
}

let teacher = Teacher(json: json[0])

print("----------------------------------")
print("姓名:\(teacher.name)      职称:\(teacher.title)")

// 将Model 转换为 JSON 或者JSONString
print("\n\n---------------请注意经过中将时间转换为了时间戳-------------------")
print("\n\(teacher.toJSON())")

------------ 运行结果 ---------
{
  "name" : "王老师",
  "id" : 17445752,
  "description" : "王老师从事大学教师职业15年,对于应用专业有很深的理解",
  "courses" : [
    {
      "description" : "王老师教学",
      "name" : "应用英语",
      "time" : 1497664800000
    },
    {
      "description" : "王老师教学",
      "name" : "应用数学",
      "time" : 1497751200000
    }
  ],
  "title" : "副教授",
  "schoolAge" : "15年",
  "homePage" : "http:\/\/www.baidu.com"
}
  • 转换时忽略schoolAge 及将description转换为desc
    你需要在Teacher这个类中实现:
    var ignoreProperties
    var replacedProperties
class Teacher: JSONMappable {
    // 此处省略JSON -> Model

    public var ignoreProperties: [String]? {
        return ["schoolAge"]
    }

    public var replacedProperties: [String : String]? {
        return ["description": "desc"]
    }
}

--------- 运行结果 ------
{
  "desc" : "王老师从事大学教师职业15年,对于应用专业有很深的理解",
  "name" : "王老师",
  "title" : "副教授",
  "id" : 17445752,
  "homePage" : "http:\/\/www.baidu.com",
  "courses" : [
    {
      "desc" : "王老师教学",
      "name" : "应用英语"
    },
    {
      "desc" : "王老师教学",
      "name" : "应用数学"
    }
  ]
}
  • 结合Moya 使用
pod 'SwiftyJSONMappable/Moya'
MoyaProvider<APIService>().request(.testGet) { (result) in
            print("\n\n--------------- 网络示例非RxSwift -------------------")
            switch result {
            case let .success(response):
                do {
                    let httpBin = try response.mapJSONMappable(HttpBin.self)
                    print(httpBin.mapString() ?? "")
                } catch {
                    print(error)
                }
            case let .failure(error):
                print(error)
            }
        }
  • 结合RxSwfit使用
pod 'SwiftyJSONMappable/RxSwift'
RxMoyaProvider<APIService>().request(.testGet)
            .mapJSONMappable(HttpBin.self)
            .observeOn(SerialDispatchQueueScheduler(internalSerialQueueName: "test"))
            .subscribe { (event) in
                switch event {
                case let .next(httpBin):
                    print("\n\n--------------- 网络示例RxSwift -------------------")
                    print(httpBin.mapString() ?? "请求完毕")
                case let .error(error):
                    print(error)
                default:
                    print(event)
                }
            }.addDisposableTo(disposeBag)

我将示例代码上传至这里,如果你觉得用起来可以,请给我一个星,谢谢



作者:一根聪
链接:https://www.jianshu.com/p/5a564585e0ea
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/yishengzhiai005/article/details/80527793