All Projects → evgenyneu → JsonSwiftson

evgenyneu / JsonSwiftson

Licence: MIT license
A JSON parser with concise API written in Swift.

Programming Languages

swift
15916 projects
objective c
16641 projects - #2 most used programming language
ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to JsonSwiftson

Simdjson
Parsing gigabytes of JSON per second
Stars: ✭ 15,115 (+107864.29%)
Mutual labels:  json-parser
xijs
A business - oriented scene Js Library
Stars: ✭ 91 (+550%)
Mutual labels:  json-parser
representable
Maps representation documents from and to Ruby objects. Includes JSON, XML and YAML support, plain properties and compositions.
Stars: ✭ 689 (+4821.43%)
Mutual labels:  json-parser
Json Dry
🌞 JSON-dry allows you to serialize & revive objects containing circular references, dates, regexes, class instances,...
Stars: ✭ 214 (+1428.57%)
Mutual labels:  json-parser
dora
JSON parser/explorer
Stars: ✭ 42 (+200%)
Mutual labels:  json-parser
jackson-js
JavaScript object serialization and deserialization library using decorators. It supports also advanced Object concepts such as polymorphism, Object identity and cyclic objects.
Stars: ✭ 86 (+514.29%)
Mutual labels:  json-parser
Jsons
🐍 A Python lib for (de)serializing Python objects to/from JSON
Stars: ✭ 178 (+1171.43%)
Mutual labels:  json-parser
coronavirus-dresden
Collects official SARS-CoV-2 infection statistics published by the city of Dresden.
Stars: ✭ 19 (+35.71%)
Mutual labels:  json-parser
Indian-States-and-Cities-Android
Offline Android App to illustrate Auto Complete Indian cities and states text views
Stars: ✭ 19 (+35.71%)
Mutual labels:  json-parser
Cerializer
JSON Serializer using compile time reflection
Stars: ✭ 16 (+14.29%)
Mutual labels:  json-parser
Thorsserializer
C++ Serialization library for JSON
Stars: ✭ 241 (+1621.43%)
Mutual labels:  json-parser
Oj
Optimized JSON
Stars: ✭ 2,824 (+20071.43%)
Mutual labels:  json-parser
ajson
Abstract JSON for Golang with JSONPath support
Stars: ✭ 144 (+928.57%)
Mutual labels:  json-parser
Json
A really simple C# JSON Parser in 350 lines
Stars: ✭ 202 (+1342.86%)
Mutual labels:  json-parser
TwoWayMirror
Adapt Swift’s Mirror functionality to make it bidirectional.
Stars: ✭ 38 (+171.43%)
Mutual labels:  json-parser
Dlib
Allocators, I/O streams, math, geometry, image and audio processing for D
Stars: ✭ 182 (+1200%)
Mutual labels:  json-parser
domino-jackson
Jackson with Annotation processing
Stars: ✭ 46 (+228.57%)
Mutual labels:  json-parser
format-to-json
An algorithm that can format a string to json-like template. 字符串JSON格式化的算法。
Stars: ✭ 30 (+114.29%)
Mutual labels:  json-parser
libstud-json
JSON pull-parser/push-serializer library for C++
Stars: ✭ 20 (+42.86%)
Mutual labels:  json-parser
jisoni
A native JSON parser written in pure @vlang/v
Stars: ✭ 13 (-7.14%)
Mutual labels:  json-parser

A JSON parser with concise API written in Swift

Carthage compatible CocoaPods Version License Platform

JsonSwiftson JSON parser for Swift

  • Maps JSON attributes to different Swift types with just two methods: map and mapArrayOfObjects.
  • The library can be used on any platform that runs Swift.
  • Supports casting to optional types.
  • Indicates if the mapping was successful.
  • Can be used in Swift apps for Apple devices and in open source Swift programs on other platforms.

Example

The following is an example of mapping a JSON text into a Swift Person structure.

struct Person {
  let name: String
  let age: Int
}

let mapper = JsonSwiftson(json: "{ \"name\": \"Peter\", \"age\": 41 }")

let person = Person(
  name: mapper["name"].map() ?? "",
  age: mapper["age"].map() ?? 0
)

if !mapper.ok { /* report error */ }

Setup (Swift 3.0)

There are four ways you can add JsonSwiftson into your project.

Add the source file (iOS 7+)

Simply add JsonSwiftson.swift file to your Xcode project.

Setup with Carthage (iOS 8+)

Alternatively, add github "evgenyneu/JsonSwiftson" ~> 4.0 to your Cartfile and run carthage update.

Setup with CocoaPods (iOS 8+)

If you are using CocoaPods add this text to your Podfile and run pod install.

use_frameworks!
target 'Your target name'
pod 'JsonSwiftson', git: 'https://github.com/evgenyneu/JsonSwiftson.git', tag: '4.0.0'

Setup with Swift Package Manager

Add the following text to your Package.swift file and run swift build.

import PackageDescription

let package = Package(
    name: "YourPackageName",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/evgenyneu/JsonSwiftson.git",
                 versions: Version(3,0,0)..<Version(4,0,0))
    ]
)

Legacy Swift versions

Setup a previous version of the library if you use an older version of Swift.

Usage

  1. Add import JsonSwiftson to your source code if you used Carthage or CocoaPods setup.

  2. Create an instance of JsonSwiftson class and supply a JSON text for parsing.

let mapper = JsonSwiftson(json: "{ \"person\": { \"name\": \"Michael\" }}")
  1. Supply the name of JSON attribute you want to get and call the map method. The type of the JSON value is inferred from the context.
let name: String? = mapper["person"]["name"].map()

The example above mapped JSON to an optional String type. One can map to a non-optional by using the ?? operator and supplying a default value.

let name: String = mapper["person"]["name"].map() ?? "Default name"
  1. Finally, check ok property to see if mapping was successful.
if !mapper.ok { /* report error */ }

The ok property will return false if JSON parsing failed or the attribute with the given name was missing. You can allow the attribute to be missing by supplying the optional: true argument to the map method.

let name: String? = mapper["person"]["name"].map(optional: true)

Map to simple Swift types

Use the map method to parse JSON to types like strings, numbers and booleans.

// String
let stringMapper = JsonSwiftson(json: "\"Hello World\"")
let string: String? = stringMapper.map()

// Integer
let intMapper = JsonSwiftson(json: "123")
let int: Int? = intMapper.map()

// Double
let doubleMapper = JsonSwiftson(json: "123.456")
let double: Double? = doubleMapper.map()

// Boolean
let boolMapper = JsonSwiftson(json: "true")
let bool: Bool? = boolMapper.map()

Map property by name

Use square brackets to reach JSON properties by name: mapper["name"].

let mapper = JsonSwiftson(json: "{ \"name\": \"Michael\" }")
let name: String? = mapper["name"].map()

One can use square brackets more than once to reach deeper JSON properties: mapper["person"]["name"].

let mapper = JsonSwiftson(json: "{ \"person\": { \"name\": \"Michael\" }}")
let name: String? = mapper["person"]["name"].map()

Map arrays of simple values

JsonSwiftson will automatically map to the arrays of strings, numbers and booleans.

// String
let stringMapper = JsonSwiftson(json: "[\"One\", \"Two\"]")
let string: [String]? = stringMapper.map()

// Integer
let intMapper = JsonSwiftson(json: "[1, 2]")
let int: [Int]? = intMapper.map()

// Double
let doubleMapper = JsonSwiftson(json: "[1.1, 2.2]")
let double: [Double]? = doubleMapper.map()

// Boolean
let boolMapper = JsonSwiftson(json: "[true, false]")
let bool: [Bool]? = boolMapper.map()

Map an array of objects

Use mapArrayOfObjects with a closure to map array of objects.

struct Person {
  let name: String
  let age: Int
}

let mapper = JsonSwiftson(json:
  "[ " +
    "{ \"name\": \"Peter\", \"age\": 41 }," +
    "{ \"name\": \"Ted\", \"age\": 51 }" +
  "]")

let people: [Person]? = mapper.mapArrayOfObjects { j in
  Person(
    name: j["name"].map() ?? "",
    age: j["age"].map() ?? 0
  )
}

Tip: Use map method instead of mapArrayOfObjects for mapping arrays of simple values like strings, numbers and booleans.

Mapping to Swift structures

struct Person {
  let name: String
  let age: Int
}

let mapper = JsonSwiftson(json: "{ \"name\": \"Peter\", \"age\": 41 }")

let person = Person(
  name: mapper["name"].map() ?? "",
  age: mapper["age"].map() ?? 0
)

Check if mapping was successful

Verify the ok property to see if mapping was successful. Mapping fails for incorrect JSON and type casting problems.

Note: map and mapArrayOfObjects methods always return nil if mapping fails.

let successMapper = JsonSwiftson(json: "\"Correct type\"")
let string: String? = successMapper.map()
if successMapper.ok { print("👏👏👏") }

let failMapper = JsonSwiftson(json: "\"Wrong type\"")
let number: Int? = failMapper.map()
if !failMapper.ok { print("🐞") }

Allow missing values

Mapping fails by default if JSON value is null or attribute is missing.

Tip: Pass optional: true parameter to allow missing JSON attributes and null values.

let mapper = JsonSwiftson(json: "{ }")
let string: String? = mapper["name"].map(optional: true)
if mapper.ok { print("👏👏👏") }

Allow missing objects

Use map method with optional: true parameter and a closure to allow empty objects.

struct Person {
  let name: String
  let age: Int
}

let mapper = JsonSwiftson(json: "null") // empty

let person: Person? = mapper.map(optional: true) { j in
  Person(
    name: j["name"].map() ?? "",
    age: j["age"].map() ?? 0
  )
}

if mapper.ok { print("👏👏👏") }

Tip: map to a non-optional type

Use ?? operator after the mapper if you need to map to a non-optional type like let number: Int.

let numberMapper = JsonSwiftson(json: "123")
let number: Int = numberMapper.map() ?? 0

let arrayMapper = JsonSwiftson(json: "[1, 2, 3]")
let numbers: [Int] = arrayMapper.map() ?? []

Performance benchmark

The project includes a demo app that runs performance benchmark. It maps a large JSON file containing 100 records. The process is repeated 100 times.

Json Swiftson performance benchmark

Alternative solutions

Here is a list of excellent libraries that can help taming JSON in Swift.

License

JsonSwiftson is released under the MIT License.

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].