Giter Site home page Giter Site logo

jason's Introduction

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.<type>:

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

The non-optional variant json.<type>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:

// 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
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:

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.

jason's People

Contributors

basememara avatar cbeloch avatar delba avatar dxpack avatar jakubknejzlik avatar misocharles avatar phimage avatar radarhere avatar reeichert avatar sunshinejr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jason's Issues

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.

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?

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)

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.

int64 support

Int is 32-bit in 32-bit platforms (e.g. iPhone 5). Could you please add int64 getter to avoid casting Int to Int64?

JSON to Model can support Arrays or Lists, Sets?

struct Shot {
    let id: Int
    let title: String

    var normalImageURL: NSURL!
    var hidpiImageURL: NSURL?

    let users: [User]? 

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

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

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

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

for example:

let users: [User]?

in Shot class

JSONKeys这个设计感觉不合理

如果我有多个数据模型,比如:User,Topic等,但是这两个数据模型里都有name这个字段,但当这两个字段的数据类型等有区别的时候,JSONKeys怎么去定义它啊?

Extensions are not included in the pod sources

Did not see this mentioned in the README, is it the intention here for people to only pull the extensions they need? Wasn't expecting to have all the operators broken with the pod update.

swift 5 support

Xcode 10.2 change min support version from swift 3 to swift 4.2 .
Has create a Pull Request
#44

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.

JASON and Realm's List types

Realm To-Many Relationships types is List. and JASON is Array OR Set.
JASON could support RealmSwift List types?

Please, release version with SPM support

Hi,

I’ve wrote Swift Package for networking (based on Combine and Alamofire) Legatus. And it's using JASON for JSON deserialization.

But in dependencies I can't set certain version of JASON, only master branch:(
.package(url: "https://github.com/delba/JASON.git", .branch("master"))

Please, create release with SPM support!🙏

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)

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):
#42

Dot notation for JSON path?

Great library, thx!

I realize I can do this to get a value from a JSON path:

thumbnailURL = json[path: "featured_image", "attachment_meta", "sizes", "thumbnail", "url"].stringValue

However, I think below seems much more convenient. Was there a reason behind leaving this out?:

thumbnailURL = json["featured_image.attachment_meta.sizes.thumbnail.url"].stringValue

Love the name

That is all :)

(Looks great, looking forward to test!)

congratulations-agree-136dgbul9Tk8Rq

How to convert to raw JSON string

I'm converting my project to go from SwiftyJSON to JASON
SwiftyJSON allows you to convert the JSON to a rawJSON string like so: json.rawString()

How can I achieve this in JASON?

Sorry for the newbie question.

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?

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.