All Projects → Pircate → Cleanjson

Pircate / Cleanjson

Licence: mit
Swift JSON decoder for Codable

Programming Languages

swift
15916 projects

Projects that are alternatives of or similar to Cleanjson

Sbjson
This framework implements a strict JSON parser and generator in Objective-C.
Stars: ✭ 3,776 (+2021.35%)
Mutual labels:  json, carthage
Swiftai
SwiftAI, write Swift code smart. SwiftAI can generate Model class from JSON now. Codable and HandyJSON is supported. More features will be add.
Stars: ✭ 470 (+164.04%)
Mutual labels:  json, codable
Json
Micro framework for easily parsing JSON in Swift with rich error messages in less than 100 lines of code
Stars: ✭ 395 (+121.91%)
Mutual labels:  json, carthage
Keyedcodable
Easy nested key mappings for swift Codable
Stars: ✭ 248 (+39.33%)
Mutual labels:  json, codable
Adaptivecardui
Snippets of UI, authored in JSON and rendered with SwiftUI
Stars: ✭ 73 (-58.99%)
Mutual labels:  json, codable
Serpent
A protocol to serialize Swift structs and classes for encoding and decoding.
Stars: ✭ 281 (+57.87%)
Mutual labels:  json, carthage
Xmlcoder
Easy XML parsing using Codable protocols in Swift
Stars: ✭ 460 (+158.43%)
Mutual labels:  codable, carthage
Localize
Localize is a framework writed in swift to localize your projects easier improves i18n, including storyboards and strings.
Stars: ✭ 253 (+42.13%)
Mutual labels:  json, carthage
Unboxedalamofire
[Deprecated] Alamofire + Unbox: the easiest way to download and decode JSON into swift objects.
Stars: ✭ 65 (-63.48%)
Mutual labels:  json, carthage
Jsontocodable
A generating tool from Raw JSON to Codable (Swift4) text written in Swift4.
Stars: ✭ 33 (-81.46%)
Mutual labels:  json, codable
Sync
JSON to Core Data and back. Swift Core Data Sync.
Stars: ✭ 2,538 (+1325.84%)
Mutual labels:  json, carthage
Codability
Useful helpers for working with Codable types in Swift
Stars: ✭ 125 (-29.78%)
Mutual labels:  json, codable
Swiftyjson
The better way to deal with JSON data in Swift.
Stars: ✭ 21,042 (+11721.35%)
Mutual labels:  json, carthage
Featureflags
🚩 Allows developers to configure feature flags, run multiple A/B tests or phase feature roll out using a JSON configuration file.
Stars: ✭ 506 (+184.27%)
Mutual labels:  json, carthage
Generic Json Swift
A simple Swift library for working with generic JSON structures
Stars: ✭ 95 (-46.63%)
Mutual labels:  json, codable
Ladybug
A powerful model framework for Swift 4
Stars: ✭ 147 (-17.42%)
Mutual labels:  json, codable
Linkedin Profile Scraper
🕵️‍♂️ LinkedIn profile scraper returning structured profile data in JSON. Works in 2020.
Stars: ✭ 171 (-3.93%)
Mutual labels:  json
Emoji.json
Just an emoji.json
Stars: ✭ 175 (-1.69%)
Mutual labels:  json
Synth
The Declarative Data Generator
Stars: ✭ 161 (-9.55%)
Mutual labels:  json
Symja android library
☕️ Symja - computer algebra language & symbolic math library. A collection of popular algorithms implemented in pure Java.
Stars: ✭ 170 (-4.49%)
Mutual labels:  json

CleanJSON

build Version Carthage compatible License Platform codebeat badge

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

只需将 JSONDecoder 替换成 CleanJSONDecoder。

Example

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

Requirements

  • iOS 9.0
  • Swift 5.2

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)

// 支持直接解析符合 JSON 规范的字典和数组
try decoder.decode(Model.self, from: ["key": value])

Enum

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

Note: 枚举使用强类型解析,关联类型和数据类型不一致不会进行类型转换,会解析为默认 case

enum Enum: Int, Codable, CaseDefaultable {
    
    case case1
    case case2
    case case3
    
    static var defaultCase: Enum {
        return .case1
    }
}

Customize decoding strategy

可以通过 valueNotFoundDecodingStrategy 在值为 null 或类型不匹配的时候自定义解码,默认策略请看这里

struct CustomAdapter: JSONAdapter {
    
    // 由于 Swift 布尔类型不是非 0 即 true,所以默认没有提供类型转换。
    // 如果想实现 Int 转 Bool 可以自定义解码。
    func adapt(_ decoder: CleanDecoder) throws -> Bool {
        // 值为 null
        if decoder.decodeNil() {
            return false
        }
        
        if let intValue = try decoder.decodeIfPresent(Int.self) {
            // 类型不匹配,期望 Bool 类型,实际是 Int 类型
            return intValue != 0
        }
        
        return false
    }
    
    // 为避免精度丢失所以没有提供浮点型转整型
    // 可以通过下面适配器进行类型转换
    func adapt(_ decoder: CleanDecoder) throws -> Int {
        guard let doubleValue = try decoder.decodeIfPresent(Double.self) else { return 0 }
        
        return Int(doubleValue)
    }
    
    // 可选的 URL 类型解析失败的时候返回一个默认 url
    func adaptIfPresent(_ decoder: CleanDecoder) throws -> URL? {
        return URL(string: "https://google.com")
    }
}

decoder.valueNotFoundDecodingStrategy = .custom(CustomAdapter())

可以通过 JSONStringDecodingStrategy 将 JSON 格式的字符串自动转成 Codable 对象或数组

// 包含这些 key 的 JSON 字符串转成对象
decoder.jsonStringDecodingStrategy = .containsKeys([])

// 所有 JSON 字符串都转成对象
decoder.jsonStringDecodingStrategy = .all

keyDecodingStrategy 新增了一个自定义映射器,可以只映射指定 coding path 的 key

decoder.keyDecodingStrategy = .mapper([
    ["snake_case"]: "snakeCase",
    ["nested", "alpha"]: "a"
])

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].