JASON is a faster JSON deserializer written in Swift.

Related tags

JSON JASON
Overview

Travis Status CocoaPods compatible Carthage compatible Platform

JASON is a faster JSON deserializer written in Swift.

JASON is the best framework we found to manage JSON at Swapcard. This is by far the fastest and
the most convenient out there, it made our code clearer and improved the global performance
of the app when dealing with large amount of data.

Gautier Gédoux, lead iOS developer at Swapcard

FeaturesUsageExampleReferencesInstallationLicense

Features

  • Very fast - benchmarks
  • Fully tested
  • Fully documented

  • Clean code
  • Beautiful API
  • Regular updates

Usage

Initialization

let json = JSON(anything) // where `anything` is `AnyObject?`

If you're using Alamofire, include JASON+Alamofire.swift in your project for even more awesomeness:

Alamofire.request(.GET, peopleURL).responseJASON { response in
    if let json = response.result.value {
        let people = json.map(Person.init)
        print("people: \(people)")
    }
}

If you're using Moya, check out Moya-JASON!

Parsing

Use subscripts to parse the JSON object:

json["people"][0]["name"]

// Or with a path:

json[path: "people", 0, "name"]

Type casting

Cast JSON value to its appropriate type by using the computed property json.:

let name = json["name"].string // the name as String?

The non-optional variant json.Value will return a default value if not present/convertible:

let name = json["wrong"].stringValue // the name will be ""

You can also access the internal value as AnyObject? if you want to cast it yourself:

let something = json["something"].object

See the References section for the full list of properties.

JSONKey:

This idea is stolen from SwiftyUserDefaults by Radek Pietruszewski (GitHub, Twitter, Blog).


> I can't recommend enough to read his article about it! 💥 [Statically-typed NSUserDefaults](http://radex.io/swift/nsuserdefaults/static/) 💥

Define and use your JSONKey as follow:

(path: 0, "twitter") let twitterURL = peopleJSON[twitterURLKey] ">
// With a int key:

let personKey = JSONKey<JSON>(0)
let personJSON = peopleJSON[personKey]

// With a string key:

let nameKey = JSONKey<String>("name")
let name = personJSON[nameKey]

// With a path:

let twitterURLKey = JSONKey<NSURL?>(path: 0, "twitter")
let twitterURL = peopleJSON[twitterURLKey]

You might find more convenient to extend JSONKeys as shown in the Example section.

See the References section for the full list of JSONKey types.

Third-party libraries:

Example

This example uses the Dribbble API (docs).


> An example of the server response can be found in [`Tests/Supporting Files/shots.json`](https://github.com/delba/JASON/blob/master/Tests/Supporting%20Files/shots.json)
  • Step 1: Extend JSONKeys to define your JSONKey
("id") static let createdAt = JSONKey("created_at") static let updatedAt = JSONKey("updated_at") static let title = JSONKey("title") static let normalImageURL = JSONKey(path: "images", "normal") static let hidpiImageURL = JSONKey(path: "images", "hidpi") static let user = JSONKey("user") static let name = JSONKey("name") } ">
JSON.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

extension JSONKeys {
    static let id    = JSONKey<Int>("id")
    static let createdAt = JSONKey<NSDate?>("created_at")
    static let updatedAt = JSONKey<NSDate?>("updated_at")

    static let title = JSONKey<String>("title")

    static let normalImageURL = JSONKey<NSURL?>(path: "images", "normal")
    static let hidpiImageURL  = JSONKey<NSURL?>(path: "images", "hidpi")

    static let user = JSONKey<JSON>("user")
    static let name = JSONKey<String>("name")
}
  • Step 2: Create the Shot and User models
struct Shot {
    let id: Int
    let title: String

    let normalImageURL: NSURL
    var hidpiImageURL: NSURL?

    let createdAt: NSDate
    let updatedAt: NSDate

    let user: User

    init(_ json: JSON) {
        id    = json[.id]
        title = json[.title]

        normalImageURL = json[.normalImageURL]!
        hidpiImageURL  = json[.hidpiImageURL]

        createdAt = json[.createdAt]!
        updatedAt = json[.updatedAt]!

        user = User(json[.user])
    }
}
struct User {
    let id: Int
    let name: String

    let createdAt: NSDate
    let updatedAt: NSDate

    init(_ json: JSON) {
        id   = json[.id]
        name = json[.name]

        createdAt = json[.createdAt]!
        updatedAt = json[.updatedAt]!
    }
}
Alamofire.request(.GET, shotsURL).responseJASON { response in
    if let json = response.result.value {
        let shots = json.map(Shot.init)
    }
}

References

Include JASON+Properties.swift for even more types!

Property JSONKey Type Default value
string String?
stringValue String ""
int Int?
intValue Int 0
double Double?
doubleValue Double 0.0
float Float?
floatValue Float 0.0
nsNumber NSNumber?
nsNumberValue NSNumber 0
cgFloat CGFloat?
cgFloatValue CGFloat 0.0
bool Bool?
boolValue Bool false
nsDate NSDate?
nsURL NSURL?
dictionary [String: AnyObject]?
dictionaryValue [String: AnyObject] [:]
jsonDictionary [String: JSON]?
jsonDictionaryValue [String: JSON] [:]
nsDictionary NSDictionary?
nsDictionaryValue NSDictionary NSDictionary()
array [AnyObject]?
arrayValue [AnyObject] []
jsonArray [JSON]?
jsonArrayValue [JSON] []
nsArray NSArray?
nsArrayValue NSArray NSArray()

Configure JSON.dateFormatter if needed for nsDate parsing

Installation

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate JASON into your Xcode project using Carthage, specify it in your Cartfile:

= 3.0 ">
github "delba/JASON" >= 3.0

CocoaPods

CocoaPods is a dependency manager for Cocoa projects.

You can install it with the following command:

$ gem install cocoapods

To integrate JASON into your Xcode project using CocoaPods, specify it in your Podfile:

use_frameworks!

pod 'JASON', '~> 3.0'

License

Copyright (c) 2015-2019 Damien (http://delba.io)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Add properties for date parsing

    Add properties for date parsing

    Properties and functions added for parsing dates with unit tests.

    For flexibility, you can let JASON parse the date using a default ISO date formatting string (yyyy-MM-dd'T'HH:mm:ss), or pass in a string format or NSDateFormatter:

    let json: JSON = [
        "date1": "2016-04-12T13:29:32",
        "date2": "16/04/2016",
        "date3": "April 10, 2020"
    ]
    
    json["date1"].dateValue
    json["date2"].dateValue("dd-MM-yyyy")
    
    let formatter = NSDateFormatter()
    formatter.dateFormat = "MMMM dd, yyyy"
    
    json["date3"].dateValue(formatter)
    

    This is related to discussion #15.

    opened by basememara 13
  • cant Parse JSON array of objects

    cant Parse JSON array of objects

    i cant parse json array objects.

    my json string is

    [{string:value,string:value},{string:value,string:value},{string:value,string:value},{string:value,string:value},{string:value,string:value},{string:value,string:value}]

    how can i parse this type of strings?

    opened by Ramachandrajoshi 4
  • JSON from String not working

    JSON from String not working

    In the playground try this (branch swift-2.0):

    import JASON
    
    let json = JSON("{\"name\": \"foo\"}")
    json["name"].stringValue
    

    I'd expect the last line to show "foo". But it doesn't.

    opened by itssimon 4
  • Argument labels do not match any available overloads

    Argument labels do not match any available overloads

    Hi, I am currently converting an app from Swift 2 to Swift 3 and was wandering of replacing the existing JSON file with the JASON framework. Here's the issue that I get screen shot 2016-11-15 at 11 06 26 pm

    opened by FogiDestructor 3
  • Carthage install broken

    Carthage install broken

    When trying to build JASON with latest version of Carthage and Xcode installed, it always fails with this error:

    *** Building scheme "JASON iOS" in JASON.xcodeproj
    /usr/bin/xcrun xcodebuild -project /Users/milanstevanovic/Developer/ios-cop/Overstats/Overstats/Carthage/Checkouts/JASON/JASON.xcodeproj -scheme "JASON iOS" -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean buildBuild settings from command line:
        BITCODE_GENERATION_MODE = bitcode
        CARTHAGE = YES
        CODE_SIGN_IDENTITY =
        CODE_SIGNING_REQUIRED = NO
        ONLY_ACTIVE_ARCH = NO
        SDKROOT = iphoneos10.0
    
    === CLEAN TARGET JASON iOS OF PROJECT JASON WITH CONFIGURATION Release ===
    
    Check dependencies
    “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.
    “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.
    
    ** CLEAN FAILED **
    
    
    The following build commands failed:
        Check dependencies
    (1 failure)
    === BUILD TARGET JASON iOS OF PROJECT JASON WITH CONFIGURATION Release ===
    
    Check dependencies
    “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.
    “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.
    
    ** BUILD FAILED **
    
    
    The following build commands failed:
        Check dependencies
    (1 failure)
    A shell task (/usr/bin/xcrun xcodebuild -project /Users/milanstevanovic/Developer/ios-cop/Overstats/Overstats/Carthage/Checkouts/JASON/JASON.xcodeproj -scheme "JASON iOS" -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
    ** CLEAN FAILED **
    
    
    The following build commands failed:
        Check dependencies
    (1 failure)
    ** BUILD FAILED **
    
    
    The following build commands failed:
        Check dependencies
    (1 failure)
    
    opened by milanstevanovic 2
  • Parsing dates?

    Parsing dates?

    I'm guessing you left out dates because it would open up a can of worms. I added an extension that works, but is inconsistent with the rest of the API's:

    extension JSON {
        public subscript(index: String, dateFormat dateFormat: String) -> NSDate? {
            let formatter = NSDateFormatter()
            formatter.dateFormat = dateFormat
    
            if let value = self[index].string,
                let date = formatter.dateFromString(value) {
                    return date
            }
    
            return nil
        }
    }
    

    Then you use it like this:

    date = json["date", dateFormat: "yyyy-MM-dd'T'HH:mm:ss"]
    

    Any thoughts or suggestions on adding support for dates?

    opened by basememara 2
  • About the JSONKeys that if both model have the same properties like 'id'

    About the JSONKeys that if both model have the same properties like 'id'

    About the JSONKeys that if both model have the same properties like 'id' example: struct User { var id = "" } struct Topic { var id = 0 } the User model called id that is a String type the Topic model called id that is a Int type.

    now, where in JSONKeys how do define it.

    opened by arden 2
  • Performance Question

    Performance Question

    The speed/performance of this library is mentioned twice:

    JASON is a faster JSON deserializer written in Swift.

    And in the quote:

    (...) This is by far the fastest and the most convenient out there (...)

    Are there any measurements/benchmarks to back these claims?

    opened by RuiAAPeres 2
  • Can you push a new version to Cocoapods with Swift 2.0 integration?

    Can you push a new version to Cocoapods with Swift 2.0 integration?

    So I am trying to use this project in my "pod" and we cannot version the dependency, would be nice if we can make a new version, like 0.3 and host this.

    opened by mohamedmansour 2
  • Add NSDictionary-to-JSON conversion benchmark.

    Add NSDictionary-to-JSON conversion benchmark.

    An ideal JSON library will maintain data as an NSDictionary internally rather than force a conversion to a Swift dictionary during init.

    On iPhone 5C, JASON runs in 0.002 sec, SwiftyJSON runs in 0.030 sec on a 10,000 item NSDictionary.

    JSON data typically originates as an NSDictionary, and converting a large NSDictionary to a Swift dictionary is slow (due to mem copy and casting of every item in the dict).

    Type conversions to Swift native types should happen only on key access, thus amortizing the cost (or avoiding the bulk conversion cost in the case where there is no consecutive loop access of every key in the JSON data).

    opened by garvankeeley 1
  • int64Value does not work on 32-bit architectures

    int64Value does not work on 32-bit architectures

    Since NSNumber is converted into Int before being made into Int64, the return value will be wrong on 32 bit architectures (happened on my iPod 5G for example).

    (From JASON+Properties.swift)

    opened by Tarpsvo 1
  • Decoding large Double

    Decoding large Double

    This code makes the exception:

    struct Response: Codable {
      let success: Bool
      let value: Double
    }
    func testJASON() {
      let string: String =
        """
        {"success":true,"value":100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000≥0}
        """
      let data = string.data(using: .utf8)!
      let json = JASON.JSON(data)
      let val = json["value"].double
      print("\(val)")
    }
    

    If you remove one of zeroes in "string" then the decoding will be OK. So the limit is 1e165, after which the decoding fails regardless of Double type can really fit.

    opened by VasilyKrainov 0
  • Fix compile error on linux

    Fix compile error on linux

    I got the following error on linux.

    .build/checkouts/JASON/Source/JSONKey.swift:26:8 error: No such module 'CoreGraphics'
    import CoreGraphics
           ^
    

    So I remove CoreGraphics dependency for linux.

    opened by 3ign0n 0
  • Benchmarks on iPhone 5C show 25% perf improvement with JASON vs. SwiftyJSON

    Benchmarks on iPhone 5C show 25% perf improvement with JASON vs. SwiftyJSON

    Running the benchmark with SwiftyJSON 3.1.4 (currently the latest) shows a 25% perf gain with JASON, on-device with a 5C.

    Just wanted to make a note for others who might be searching for on-device benchmarks, feel free to close the issue.

    Related: the following test case shows a 15x speed improvement with JASON over SwiftyJSON in what I have found to be the most frequent bottleneck in my projects (large NSDictionary data objects): https://github.com/delba/JASON/pull/42

    opened by garvankeeley 0
  • Would it be possible to include extensions as subspecs?

    Would it be possible to include extensions as subspecs?

    From what I gather by reading #25, the recommended practice is to copy-paste source code instead of using a package manager if you want any of the extensions.

    Perhaps the extensions could be supplied through subspecs in CocoaPods? It is how PromiseKit handles extensions https://github.com/mxcl/PromiseKit#extensions.

    Carthage does not support subspecs, but you can emulate the behavior by having a separate repository for the optional dependencies. You can still have keep them in one repository by using git submodules.

    opened by Burgestrand 1
Releases(v1.1)
  • v1.1(Dec 7, 2015)

  • v1.0(Nov 2, 2015)

    Support for Swift 2.1

    Installation via Carthage:

    github "delba/JASON" >= 1.0
    

    Installation via CocoaPods:

    use_frameworks!
    
    pod 'JASON', '~> 1.0'
    
    Source code(tar.gz)
    Source code(zip)
  • v0.2(Sep 3, 2015)

    Distribution
    • CocoaPods support https://github.com/delba/JASON/commit/23a4f99886d1b47cf048edeee02149cad755f3a5
    • OSX support https://github.com/delba/JASON/commit/fa6c189e8849112d9a694149d2590f10b2f2b4e8
    New features
    • Add jsonArray / jsonArrayValue properties https://github.com/delba/JASON/commit/512f774ab785135870446d8557f16b5d899f00f8
    • Add jsonDictionary / jsonDictionaryValue properties https://github.com/delba/JASON/commit/512f774ab785135870446d8557f16b5d899f00f8
    Optimizations
    • Lazy iteration https://github.com/delba/JASON/commit/512f774ab785135870446d8557f16b5d899f00f8
    Source code(tar.gz)
    Source code(zip)
Owner
Damien
Damien
Swift-json - High-performance json parsing in swift

json 0.1.4 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
JSON-Practice - JSON Practice With Swift

JSON Practice Vista creada con: Programmatic + AutoLayout Breve explicación de l

Vanesa Giselle Korbenfeld 0 Oct 29, 2021
Ss-json - High-performance json parsing in swift

json 0.1.1 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON.

JSONFeed Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON. For more information about this new feed format visit: https:/

Toto Tvalavadze 31 Nov 22, 2021
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
HandyJSON is a framework written in Swift which to make converting model objects to and from JSON easy on iOS.

HandyJSON To deal with crash on iOS 14 beta4 please try version 5.0.3-beta HandyJSON is a framework written in Swift which to make converting model ob

Alibaba 4.1k Dec 29, 2022
Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift.

Himotoki Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift. This library is highly inspired by the popular Swift JSON parsin

IKEDA Sho 799 Dec 6, 2022
ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects to and from JSON.

ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Tristan Himmelman 9k Jan 2, 2023
A type-safe JSON-RPC 2.0 library purely written in Swift

JSONRPCKit JSONRPCKit is a type-safe JSON-RPC 2.0 library purely written in Swift. // Generating request JSON let batchFactory = BatchFactory(version:

Shinichiro Oba 178 Mar 18, 2022
An extremely simple JSON helper written in Swift.

Alexander Alexander is an extremely simple JSON helper written in Swift. It brings type safety and Foundation helpers to the cumbersome task of JSON u

HODINKEE 36 Sep 15, 2022
Simple JSON Object mapping written in Swift

ObjectMapper ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Tristan Himmelman 9k Jan 2, 2023
An iOS framework for creating JSON-based models. Written in Swift.

An iOS framework for creating JSON-based models. Written in Swift (because it totally rules!) Requirements iOS 8.0+ Xcode 7.3 Swift 2.2 Installation E

Oven Bits 448 Nov 8, 2022
A JSON parser with concise API written in Swift.

A JSON parser with concise API written in Swift Maps JSON attributes to different Swift types with just two methods: map and mapArrayOfObjects. The li

Evgenii Neumerzhitckii 14 Aug 13, 2018
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
AlamofireObjectMappe - An Alamofire extension which converts JSON response data into swift objects using ObjectMapper

AlamofireObjectMapper An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper. Usage Given a U

Tristan Himmelman 2.6k Dec 29, 2022
Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable

Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable. Elevate should no longer be used for

Nike Inc. 611 Oct 23, 2022
Freddy - A reusable framework for parsing JSON in Swift.

Why Freddy? Parsing JSON elegantly and safely can be hard, but Freddy is here to help. Freddy is a reusable framework for parsing JSON in Swift. It ha

Big Nerd Ranch 1.1k Jan 1, 2023
[Deprecated] A shiny JSON parsing library in Swift :sparkles: Loved by many from 2015-2021

?? Deprecation Notice ?? Gloss has been deprecated in favor of Swift's Codable framework. The existing Gloss source is not going away, however updates

Harlan Kellaway 1.6k Nov 24, 2022