Skip to content

Simple and rugged Swift JSON Data -> Object(s) mapper.

License

Notifications You must be signed in to change notification settings

theisegeberg/BasicJSON

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This is deprecated. Now that JSON encoding and decoding can be done directly through the Codable related protocols in Swift.

BasicJSON

An oversimplified Swift JSON Data -> Object mapping framework. Works well with the BasicNetwork library.

Installation

Add repository as submodule.

git submodule add git@github.com:theisegeberg/BasicJSON.git

Drag project into your own project and add the binary.

Example use

Convert data to JSON

let singlePost:Data = Single JSON object as data...
let multiplePosts:Data = List of JSON objects as data...

// Single objects
do {
    if case .object(let rawJSON) = try singlePost.JSON() {
        let post:Post = JSON.buildObject(rawJSON: rawJSON)
        print(post)
    }
} catch let error {
    print(error.localizedDescription)
    
}

// Lists
do {
    if case .list(let rawJSONList) = try multiplePosts.JSON() {
        let posts:[Post] = JSON.buildList(rawJSON: rawJSONList)
        print(posts)
    }
} catch let error {
    print(error.localizedDescription)
    
}

Implement JSONObject protocol

import Foundation
import BasicJSON

struct Location:JSONObject {

    let latitude:Double
    let longitude:Double

    init() {
        latitude = 0
        longitude = 0
    }

    init(json: PureJSON) {
        latitude = json["latitude"].jsonValue()
        longitude = json["longitude"].jsonValue()
    }

}

struct Post:JSONObject {

    let title:String
    let location:Location
    let userId:Int
    let body:String
    let show:Bool

    init() {
        title = ""
        location = Location()
        userId = 0
        body = ""
        show = false
    }

    init(json: PureJSON) {
        title = json["title"].jsonValue()
        location = Location(json: json["location"].jsonValue())
        userId = json["userId"].jsonValue()
        body = json["body"].jsonValue()
        show = json["show"].jsonValue()
    }
}

About

Simple and rugged Swift JSON Data -> Object(s) mapper.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages