All Projects → lucianomarisi → JSONUtilities

lucianomarisi / JSONUtilities

Licence: MIT license
Easily load JSON objects and decode them into structs or classes

Programming Languages

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

Projects that are alternatives of or similar to JSONUtilities

orika-spring-boot-starter
Spring Boot Starter for Orika.
Stars: ✭ 116 (+103.51%)
Mutual labels:  mapping, mapper
Agilemapper
A zero-configuration, highly-configurable, unopinionated object mapper with viewable execution plans. Flattens, unflattens, deep clones, merges, updates and projects queries. Targets .NET 3.5+ and .NET Standard 1.0+
Stars: ✭ 345 (+505.26%)
Mutual labels:  mapping, mapper
awesome-maps-ukraine
A curated list of maps of Ukraine, ukrainian mappers and tools that they use or develop for creating and publish maps
Stars: ✭ 35 (-38.6%)
Mutual labels:  mapping, mapper
Serpent
A protocol to serialize Swift structs and classes for encoding and decoding.
Stars: ✭ 281 (+392.98%)
Mutual labels:  mapper, decoding
Mapster
A fast, fun and stimulating object to object Mapper
Stars: ✭ 1,375 (+2312.28%)
Mutual labels:  mapping, mapper
Arrow
🏹 Parse JSON with style
Stars: ✭ 355 (+522.81%)
Mutual labels:  mapping, decoding
Poiji
🍬 A tiny library converting excel rows to a list of Java objects based on Apache POI
Stars: ✭ 255 (+347.37%)
Mutual labels:  mapping, mapper
Jmapper Core
Elegance, high performance and robustness all in one java bean mapper
Stars: ✭ 159 (+178.95%)
Mutual labels:  mapping, mapper
Object Mapper
ObjectMapper is a class for automatic object mapping in Python
Stars: ✭ 72 (+26.32%)
Mutual labels:  mapping, mapper
Mappinggenerator
🔄 "AutoMapper" like, Roslyn based, code fix provider that allows to generate mapping code in design time.
Stars: ✭ 831 (+1357.89%)
Mutual labels:  mapping, mapper
Bull
BULL - Bean Utils Light Library
Stars: ✭ 150 (+163.16%)
Mutual labels:  mapping, mapper
Batmap
🦇 Convention-based, fast object mapper.
Stars: ✭ 210 (+268.42%)
Mutual labels:  mapping, mapper
ajson
Yet another json parser serializer for ABAP
Stars: ✭ 29 (-49.12%)
Mutual labels:  json-parser
gracidea
🌺 A Pokémon 2D live map gathering all regions, including wandering pokémons and characters and animated tiles!
Stars: ✭ 163 (+185.96%)
Mutual labels:  mapping
ZeroDepJson
A .NET Json parser in one .cs file, with zero dependencies.
Stars: ✭ 20 (-64.91%)
Mutual labels:  json-parser
marshmallow-objects
Marshmallow Objects and Models
Stars: ✭ 37 (-35.09%)
Mutual labels:  json-parser
esri-experiments
Fly in space and look across the sea: demos and experiments with the ArcGIS API for JavaScript
Stars: ✭ 29 (-49.12%)
Mutual labels:  mapping
pycayennelpp
A Cayenne Low Power Payload (CayenneLPP) decoder and encoder for Python
Stars: ✭ 17 (-70.18%)
Mutual labels:  decoding
CodableWrapper
@codec("encoder", "decoder") var cool: Bool = true
Stars: ✭ 143 (+150.88%)
Mutual labels:  mapping
mikrotik-json-parser
JSON parser library for RouterOS
Stars: ✭ 41 (-28.07%)
Mutual labels:  json-parser

JSONUtilities

Build Status codecov.io Carthage Compatible Swift Version

Easily load JSON objects and decode them into structs or classes. The json(atKeyPath:) function infers the type from the constant or variable definition to decode meaning no casting is needed. Both string keys and keypaths (keys separated by dots .) are supported when decoding JSON.

  • Check out the Example.playground inside the JSONUtilities.xcodeproj for a working example

Installation

CocoaPods:

Add the line pod 'JSONUtilities' to your Podfile.

Carthage:

Add the line github "lucianomarisi/JSONUtilities" to your Cartfile.

Manual:

Add the files inside the Sources folder into your Xcode project.

Swift Package Manager:

Add the line .Package(url: "https://github.com/lucianomarisi/JSONUtilities", majorVersion: 3) to your Package.swift.

Types supported

JSON raw types:

  • Int
  • Double
  • Float
  • String
  • Bool
  • [String: AnyObject]
  • RawRepresentable enums

Array of JSON raw types:

  • [Int]
  • [Double]
  • [Float]
  • [String]
  • [Bool]
  • [[String: AnyObject]]
  • [RawRepresentable]

Custom JSON objects and custom JSON object arrays

e.g. if MyClass and MyStruct conform to JSONObjectConvertible protocol

  • MyClass
  • [MyClass]
  • MyStruct
  • [MyStruct]

Typed dictionaries with a String key

  • [String: JSONRawType]
  • [String: JSONObjectConvertible]
  • [String: JSONPrimitiveConvertible]
  • [String: RawRepresentable]

InvalidItemBehaviour

When decoding arrays or dictionaries an invalidItemBehaviour parameter can be passed which controls what happens when an error occurs while decoding child items

  • .remove this will simply remove the item from the array or dictionary. This is the default
  • .fail if any of the children encounter an error the whole array or dictionary decoding will fail. For optional properties this means the array or dictionary will return nil, and for non optional properties it will throw an error
  • .value(T) Provide an alternative value
  • .custom((DecodingError) -> InvalidItemBehaviour) Lets you specify the behaviour based on the specific DecodingError

Examples of JSON loading

From file

let filename = "myjsonfile"
let dictionary: [String: AnyObject] = try JSONDictionary.from(filename: filename)

From data

let data: Data = ...
let dictionary: [String: AnyObject] = try JSONDictionary.from(jsonData: data)

Examples of JSON decoding

Consider a JSON object that represents a person:

{
  "name" : "John Doe",
  "age" : 24,
  "weight" : 72.4
}

Decode JSON inline

let jsonDictionary = try JSONDictionary.from(filename: "person.json")
let name: String = try jsonDictionary.json(atKeyPath: "name")
let age: Int = try jsonDictionary.json(atKeyPath: "age")
let weight: Int = try jsonDictionary.json(atKeyPath: "weight")
let profession: String? = jsonDictionary.json(atKeyPath: "profession") // Optional decoding

Decode structs or classes

struct Person { //OR class Person {

  let name: String
  let age: Int
  let weight: Double
  let profession: String?

  init(jsonDictionary: JSONDictionary) throws {
    name = try jsonDictionary.json(atKeyPath: "name")
    age = try jsonDictionary.json(atKeyPath: "age")
    weight = try jsonDictionary.json(atKeyPath: "weight")
    profession = jsonDictionary.json(atKeyPath: "profession")
  }

}

Decode nested structs or classes by conforming to the JSONObjectConvertible protocol

Consider a company JSON object:

{
    "name" : "Working name LTD.",
    "employees": [
        {
            "name": "John Doe",
            "age": 24,
            "weight": 72.4
        },
        {
            "name": "Jane Doe",
            "age": 22,
            "weight": 70.1
        }
    ]
}

The Company struct can decode an array of Person structs/classes by making Person conform to the JSONObjectConvertible protocol

struct Company {
  let name: String
  let employees: [Person]

  init(jsonDictionary: JSONDictionary) throws {
    name = try jsonDictionary.json(atKeyPath: "name")
    employees = try jsonDictionary.json(atKeyPath: "employees")
  }
}

Support custom primitive types by conforming to JSONPrimitiveConvertible

Any type can extend the JSONPrimitiveConvertible protocol in order to allow decoding. For example extending URL: Note that this extension come out of the box :

extension URL: JSONPrimitiveConvertible {

  public typealias JSONType = String

  public static func from(jsonValue: String) -> Self? {
    return self.init(string: jsonValue)
  }

}

let urlDictionary = ["url": "www.google.com"]
let url: URL = try! urlDictionary.json(atKeyPath: "url") // www.google.com

It's also possible to have an array of JSONPrimitiveConvertible values, for example:

let urlsDictionary = ["urls": ["www.google.com", "www.yahoo.com"]]
let urls: [URL] = try! urlsDictionary.json(atKeyPath: "urls") // [www.google.com, www.yahoo.com]
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].