SwiftyJSON decoder for Codable

Overview

SwiftyJSONDecoder

CI Status Version License Platform

功能

继承自 JSONDecoder,在标准库源码基础上做了改动,与其主要区别如下

  • 使用 SwiftyJSON 解析数据,使用其类型兼容功能
  • 废弃 nonConformingFloatDecodingStrategy 属性设置,DoubleFloat 默认解析 inf infinity -inf -infinity nan数据
  • 增加新策略 nonOptionalDecodingStrategy,默认为 automatically
    • automatically:当解析非optional类型时,其值为 null,自动填充默认值
    • throw:当解析非optional类型时,其值为 null,抛出异常
  • 增加 DefaultCaseCodable 协议,当 enum 实现此协议,当解析失败时将使用此默认值
  • CodingKey 支持用 . 分割 keypath,从而通过 keypath 解析数据

Example

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

Usage

SwiftyJSONDecoder 直接替换 JSONDecoder

Import

import SwiftyJSONDecoder

Normal

struct Book: Codable {
    var title: String = ""
    var price: Int = 0
    var author: String?
    var isNew: Bool = false
    var tags: [Int] = []
}

it("Model") {
    let json = """
{
"title": "ABCDEF",
"price": 10,
"isNew": 1,
"author": null,
"tags": [1, 2, 3, 4]
}
"""
    do {
        let book = try SwiftyJSONDecoder().decode(Book.self, from: json)
        expect(book.title) == "ABCDEF"
        expect(book.price) == 10
        expect(book.isNew) == true
        expect(book.author == nil) == true
        expect(book.tags) == [1, 2, 3, 4]
    } catch {
        fail("解析失败")
    }
}

DefaultCaseCodable

enum BookType: Int, Codable, DefaultCaseCodable {
    case history
    case action

    static var defaultCase: Self {
        return .history
    }
}

let json = """
[0, 1, 2, ""]
"""
do {
    let values = try SwiftyJSONDecoder().decode([BookType].self, from: json)
    expect(values) == [.history, .action, .history, .history]
} catch {
    fail("解析失败")
}

CodingKey 支持 keypath

struct A: Codable {
    var value: String
    enum CodingKeys: String, CodingKey {
        case value = "A.B.C.D.F"
    }
}

let json = """
{"A": {"B": {"C": {"D": {"F": "ABCDEFG"}}}}}
"""
do {
    let value = try SwiftyJSONDecoder().decode(A.self, from: json)
    expect(value.value) == "ABCDEFG"
} catch {
    fail("解析失败")
}

Requirements

iOS 9+ Swift 5.0+ Xcode 13(如需在以下版本使用,可使用 1.0 版本)

Installation

SwiftyJSONDecoder is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'SwiftyJSONDecoder'

License

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

You might also like...
A video decoder built on ffmpeg which allows libpag to use ffmpeg as its software decoder for h264 decoding.

ffavc ffavc is a video decoder built on ffmpeg which allows libpag to use ffmpeg as its software decoder for h264 decoding. Build ffmpeg First, make s

Codable, but with Super power made custom Codable behavior easy.

Codable, but with Super power made custom Codable behavior easy.

SwiftyJSON makes it easy to deal with JSON data in Swift.

SwiftyJSON SwiftyJSON makes it easy to deal with JSON data in Swift. Platform Build Status *OS Linux Why is the typical JSON handling in Swift NOT goo

The better way to deal with JSON in Objective-C (inspired by SwiftyJSON)

NSTEasyJSON Inpired by SwiftyJSON. NSTEasyJSON makes it easy to deal with JSON data in Objective-C. Why is the typical JSON handling in Objective-C NO

Alamofire extension for serialize NSData to SwiftyJSON

Alamofire-SwiftyJSON An extension to make serializing Alamofire's response with SwiftyJSON easily. ⚠️ To use with Swift 3.x please ensure you are usin

Swift guarded model initializers for SwiftyJSON

GuardedSwiftyJSON Why should I use this? This library makes initializing models with JSON data with SwiftyJSON a lot easier. Often with SwiftyJSON I e

JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

PMJSON provides a pure-Swift strongly-typed JSON encoder/decoder

Now Archived and Forked PMJSON will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PMJS

The easy to use Swift JSON decoder
The easy to use Swift JSON decoder

Unbox is deprecated in favor of Swift’s built-in Codable API and the Codextended project. All current users are highly encouraged to migrate to Codable as soon as possible.

Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.
Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.

YLGIFImage Asynchronized GIF image class and Image viewer supporting play/stop GIF images. It just use very less memory. Following GIF usually will co

A enhanced JSON decoder.

JSONDecoderEx A enhanced JSON decoder. Usage struct User: Codable { struct Role: OptionSet, Codable, CustomStringConvertible { let rawValu

Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die
Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very imp

Dogtector: dog breed detection app for iOS using YOLOv5 model combined with Metal based object decoder optimized
Dogtector: dog breed detection app for iOS using YOLOv5 model combined with Metal based object decoder optimized

Dogtector Project description Dogtector is dog breed detection app for iOS using YOLOv5 model combined with Metal based object decoder optimized for u

iCalSwift - iCalendar(RFC 5545) encoder and decoder for Swift

iCalSwift - iCalendar(RFC 5545) encoder and decoder for Swift

A enhanced JSON decoder.

JSONDecoderEx A enhanced JSON decoder. Usage struct User: Codable { struct Role: OptionSet, Codable, CustomStringConvertible { let rawValu

A Collection of PropertyWrappers to make custom Serialization of Swift Codable Types easy

CodableWrappers Simplified Serialization with Property Wrappers Move your Codable and (En/De)coder customization to annotations! struct YourType: Coda

CodableCSV - Read and write CSV files row-by-row or through Swift's Codable interface.

CodableCSV provides: Imperative CSV reader/writer. Declarative CSV encoder/decoder. Support multiple inputs/outputs: Strings, Data blobs, URLs, and St

Default is a Modern interface to UserDefaults + Codable support
Default is a Modern interface to UserDefaults + Codable support

Default is a library that extends what UserDefaults can do by providing extensions for saving custom objects that conform to Codable and also providing a new interface to UserDefaults described below, via the protocol DefaultStorable. You can use only the Codable support extensions or the DefaultStorable protocol extensions or both. (or none, that's cool too)

tl;dr You love Swift's Codable protocol and use it everywhere
tl;dr You love Swift's Codable protocol and use it everywhere

tl;dr You love Swift's Codable protocol and use it everywhere, who doesn't! Here is an easy and very light way to store and retrieve -reasonable amoun

Owner
null
The better way to deal with JSON in Objective-C (inspired by SwiftyJSON)

NSTEasyJSON Inpired by SwiftyJSON. NSTEasyJSON makes it easy to deal with JSON data in Objective-C. Why is the typical JSON handling in Objective-C NO

Timur Bernikovich 11 Apr 2, 2020
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

John Lui 454 Oct 30, 2022
PMJSON provides a pure-Swift strongly-typed JSON encoder/decoder

Now Archived and Forked PMJSON will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PMJS

Postmates Inc. 364 Sep 28, 2022
The easy to use Swift JSON decoder

Unbox is deprecated in favor of Swift’s built-in Codable API and the Codextended project. All current users are highly encouraged to migrate to Codable as soon as possible.

John Sundell 2k Dec 31, 2022
A enhanced JSON decoder.

JSONDecoderEx A enhanced JSON decoder. Usage struct User: Codable { struct Role: OptionSet, Codable, CustomStringConvertible { let rawValu

SAGESSE-CN 105 Dec 19, 2022
Dogtector: dog breed detection app for iOS using YOLOv5 model combined with Metal based object decoder optimized

Dogtector Project description Dogtector is dog breed detection app for iOS using YOLOv5 model combined with Metal based object decoder optimized for u

Bartłomiej Pluta 21 Aug 1, 2022
A enhanced JSON decoder.

JSONDecoderEx A enhanced JSON decoder. Usage struct User: Codable { struct Role: OptionSet, Codable, CustomStringConvertible { let rawValu

SAGESSE-CN 105 Dec 19, 2022
Library of Swiftui Views conforming to Codable, meaning we can produce JSON driven UI!

CodableView Library of Swiftui Views conforming to Codable, meaning we can produce JSON driven UI! Adding a CodableView Type Create View that conforms

Daniel Bolella 3 Apr 2, 2022
Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs

Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs.

Julio Cesar Guzman Villanueva 2 Oct 6, 2022
Implement dynamic JSON decoding within the constraints of Swift's sound type system by working on top of Swift's Codable implementations.

DynamicCodableKit DynamicCodableKit helps you to implement dynamic JSON decoding within the constraints of Swift's sound type system by working on top

SwiftyLab 15 Oct 16, 2022