A JSON parser with concise API written in Swift.

Overview

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.

You might also like...
Weather - Weather app to practice using CoreLocation, fetching data from openweathermap.org API, JSON decoding, applying day\night appearance
WPArticleView - SwiftUI View for Wordpress JSON API

WPArticleView Installation ... dependencies: [ .package(url: "https://github

πŸ“± A comprehensive test task for creating an autolayout interface, requesting an API and JSON parsing from Effective Mobile.
πŸ“± A comprehensive test task for creating an autolayout interface, requesting an API and JSON parsing from Effective Mobile.

ECOMMERCE A comprehensive test task for creating an autolayout interface, requesting an API and JSON parsing from Effective Mobile. πŸ‘©β€πŸŽ¨ Design ✨ Fea

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

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

JASON is a faster JSON deserializer written in Swift.
JASON is a faster JSON deserializer written in Swift.

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

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

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:

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

Releases(2.0.3)
Owner
Evgenii Neumerzhitckii
πŸ‹πŸ¦”πŸ’πŸwow
Evgenii Neumerzhitckii
Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend. Using Argo

thoughtbot, inc. 3.5k Dec 20, 2022
JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift.

JSEN /ˈdΚ’eΙͺsΙ™n/ JAY-sΙ™n JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift. A JSON, as defined in the EC

Roger Oba 8 Nov 22, 2022
Jay - Pure-Swift JSON parser & formatter. Fully streamable input and output. Linux & OS X ready.

Pure-Swift JSON parser & formatter. Fully streamable input and output. Linux & OS X ready. Replacement for NSJSONSerialization.

Danielle 132 Dec 5, 2021
Functional JSON Parser - Linux Ready

Functional JSON Parser Feature Linux Ready Type-safe JSON parsing Functional value transformation Easy to parse nested value Dependency free No define

Ryo Aoyama 117 Sep 9, 2022
This framework implements a strict JSON parser and generator in Objective-C.

SBJson 5 Chunk-based JSON parsing and generation in Objective-C. Overview SBJson's number one feature is stream/chunk-based operation. Feed the parser

null 3.8k Jan 5, 2023
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
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
Developed with use Swift language. As a third party library used SDWebImage. JSON parsing using URLSession with TMDB API. This app provide by the Core Data structure.

Capstone Project ?? About Developed with use Swift language. As a third party library used SDWebImage. JSON parsing using URLSession with TMDB API. Ad

Ensar Batuhan Unverdi 9 Aug 22, 2022