Giter Club home page Giter Club logo

jsonreader's Introduction

JsonReader

Swift 4.0 offers a great way to read Json files since JSONSerialization can turn a Data into a value of type Any that can be cast into an array, a dictionnary or every other type of variable found in a json file.

We can basically read json from a data like this :

let jsonContent = """
    {
        \"person\" : [
            {
                \"name\": \"Bob\",
                \"age\": 16,
                \"employed\": false,
                \"nil\": null
            },
            {
                \"name\": \"Vinny\",
                \"age\": 56,
                \"employed\": true
            }
        ]
    }
"""

print(jsonContent)

let data = jsonContent.data(using: .utf8)!

let jsonResult = try JSONSerialization.jsonObject(with: data,
                                                  options: .mutableContainers)

The only problem with this approach is that we have to cast our object of type Any into a lot of differents types.

The point of this package is to turn a big syntax like this :

if let dictionnary = jsonResult as? [String: Any] {
    if let array = dictionnary["person"] as? [Any] {
        if let secondDictionnary = array[0] as? [String: Any] {
            if let name = secondDictionnary["name"] as? String {
                print(name)
            }
        }
    }
}

Into something like this :

let object = JsonObject(json: jsonResult)
if let name = object["person"]?[0]?["name"]?.stringValue {
    print(name)
}

To do so, we turn the json result into an enumeration that define which type it is :

indirect enum JsonObject {
    case dictionnary([String: JsonObject])
    case array([JsonObject])
    case string(String)
    case integer(Int)
    case float(Double)
    case none
    
    [...]

We can create instances directly from the result of the JSONSerialisation method using the init with Any :

    init(json: Any) {
        [...]
    }

Two subscript methods are present. One taking a String and assuming we're using a dictionnary and one taking an Int and assuming we're an array. Both of them will return nil if it's not the case. The Dictionary will return nil if the key doesn't exist and the Array will return nil if the index is too high.

    subscript(key: String) -> JsonObject? {
        [...]
    }
    
    subscript(index: Int) -> JsonObject? {
        [...]
    }

This enumeration is conform to the protocols Equatable and CustomStringConvertible wich description will return a JSON formatted string describing itself.

So this code bellow will simply show "I'm equal to myself" :

let recastedObject = JsonObject(json: try! JSONSerialization.jsonObject(with: object.description.data(using: .utf8)!, options: .allowFragments))
if object == recastedObject {
    print("I'm equal to myself")
}

jsonreader's People

Contributors

acarotin avatar amasson42 avatar

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.