JSON

0.16.1

The fastest Native Swift JSON available
vdka/JSON

What's New

2016-10-27T06:13:34Z

JSON

Language Build Status

This is Not just Another Swift JSON Package. This is the Swift JSON Package. When you are transforming directly to models this framework is faster than Foundation.JSONSerialization.

Time to Parse and initialize a struct from a sample 432KB JSON file.

Foundation vdka/json
Time 149.7ms 27.03ms
LOC 71 35

Tests run on Darwin (Linux Foundation is even slower) built with -Ounchecked

Type safety can get you a long way, lets see how you can use it for your applications.

enum Currency: String { case AUD, EUR, GBP, USD }

struct Money {
  var minorUnits: Int
  var currency: Currency

}

struct Person {
  var name: String
  var age: Int
  var accountBalances: [Money]
  var petName: String?
}

extension Money: JSONConvertible {

  func encoded() -> JSON {
    return
      [
        "minorUnits": minorUnits,
        "currencyCode": currency.encoded()
    ]
  }

  init(json: JSON) throws {
    self.minorUnits = try json.get("minorUnits")
    self.currency   = try json.get("currencyCode")
  }
}


extension Person: JSONConvertible {

  func encoded() -> JSON {
    return
      [
        "name": name,
        "age": age,
        "accountBalances": accountBalances.encoded()
    ]
  }

  init(json: JSON) throws {
    self.name             = try json.get("name")
    self.age              = try json.get("age")
    self.accountBalances  = try json.get("accountBalances")
    self.petName          = try json.get("petName")
  }
}

Alternative Access Patterns

Subscripting

json["pet"]?["vets"]?[0]?["name"]?.string

json["pet"]["vets"][0]["name"].string is also valid however this one has to perform runtime type checks making it much slower. This will probably be deprecated at least until we can constrain Generic Type extensions to Specific types.

Description

  • Swift Tools 3.1.0
View More Packages from this Author

Dependencies

  • None
Last updated: Mon Jan 30 2023 00:30:24 GMT-1000 (Hawaii-Aleutian Standard Time)