Latest 0.5.1
Homepage https://github.com/Pircate/CleanJSON
License MIT
Platforms ios 9.0, osx 10.10, tvos 9.0, watchos 2.0
Authors

CI Status
Version
Carthage compatible
License
Platform

继承自 JSONDecoder,在标准库源码基础上做了改动,以解决 JSONDecoder 各种解析失败的问题,如键值不存在,值为 null,类型不一致。

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

  • iOS 9.0+
  • Swift 4

Installation

CleanJSON is available through CocoaPods or Carthage. To install
it, simply add the following line to your Podfile or Cartfile:

Podfile

pod 'CleanJSON'

Cartfile

github "Pircate/CleanJSON"

Import

import CleanJSON

Usage

Normal

let decoder = CleanJSONDecoder()
try decoder.decode(Model.self, from: data)

对于不可选的枚举类型请遵循 CaseDefaultable 协议,如果解析失败会返回默认 case

enum Enum: Int, Codable, CaseDefaultable {

    case case1
    case case2
    case case3

    static var defaultCase: Enum {
        return .case1
    }
}

Custom type convertion

可以通过 typeConvertionStrategy 自定义类型转换,仅在值为 null 或类型不一致的时候生效,默认规则请看这里

下面代码设定在解析的时候将 JSON 的 Int 类型 转换为 swift 的 Bool 类型

decoder.typeConvertionStrategy.convertToBool = { decoder in
    if let intValue = try decoder.decode(Int.self) {
        return intValue != 0
    }
    return false
}

For Moya

使用 Moya.Response 自带的 map 方法解析,传入 CleanJSONDecoder

provider = MoyaProvider<GitHub>()
provider.request(.zen) { result in
    switch result {
    case let .success(response):
        let decoder = CleanJSONDecoder()
        let model = response.map(Model.self, using: decoder)
    case let .failure(error):
        // this means there was a network failure - either the request
        // wasn't sent (connectivity), or no response was received (server
        // timed out).  If the server responds with a 4xx or 5xx error, that
        // will be sent as a ".success"-ful response.
    }
}

For RxMoya

provider = MoyaProvider<GitHub>()
let decoder = CleanJSONDecoder()
provider.rx.request(.userProfile("ashfurrow"))
    .map(Model.self, using: decoder)
    .subscribe { event in
        switch event {
        case let .success(model):
            // do someting
        case let .error(error):
            print(error)
        }
    }

Author

Pircate, [email protected]

License

CleanJSON is available under the MIT license. See the LICENSE file for more info.

Latest podspec

{
    "name": "CleanJSON",
    "version": "0.5.1",
    "summary": "Custom JSON decoder for Decodable.",
    "homepage": "https://github.com/Pircate/CleanJSON",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "authors": {
        "Pircate": "[email protected]"
    },
    "source": {
        "git": "https://github.com/Pircate/CleanJSON.git",
        "tag": "0.5.1"
    },
    "platforms": {
        "ios": "9.0",
        "osx": "10.10",
        "tvos": "9.0",
        "watchos": "2.0"
    },
    "swift_version": "4.2",
    "source_files": "CleanJSON/Classes/**/*"
}

Pin It on Pinterest

Share This