Skip to content

kevin-lyn/Ditto

Repository files navigation

Ditto CI Status Version Carthage Swift Pacakge Manager License

Ditto allows you to serialize your swift object to JSON object compatible dictionary.

Features

  • Customizable mapping.
  • Auto mapping with frequently used mapping style.
  • Custom type convertible supported.
  • Nested serializable.

Requirements

  • Xcode 8.0+
  • Swift 3.0

Usage

CocoaPods

pod 'Ditto-Swift'

Carthage

github "kevin0571/Ditto"

Swift Package Manager

dependencies: [
    .Package(url: "https://github.com/kevin0571/Ditto.git", majorVersion: 1)
]

Overview

import Ditto

struct ExampleStruct {
    let string = "string"
    let anotherString = "anotherString"
    let int = 1
    let url = URL(string: "https://github.com")
}

extension ExampleStruct: Serializable {
    func serializableMapping() -> Mapping {
        return [
            "string": "str",
            "int": "integer",
            "url": "url"
        ]
    }
}

// Serialize ExampleStruct
let exampleStruct = ExampleStruct()

// To Dictionary
let jsonObject: JSONObject = exampleStruct.serialize()
let jsonArray: [JSONObject] = [exampleStruct, exampleStruct].serialize()
/*
 "jsonObject" will be a dictionary with content:
 [
    "str": "string",
    "integer": 1,
    "url": "https://github.com"
 ]
 note that "anotherString" is not being serialized,
 becuase mapping of "anotherString" is not defined in "serializableMapping".
 */
 
// To String
let jsonObjectString: String = exampleStruct.serialize()

// To Data
let jsonObjectData: Data = exampleStruct.serialize()

Auto Mapping

Available auto mapping styles: lowercaseSeparatedByUnderScore, lowercase, lowerCamelCase, upperCamelCase

extension ExampleStruct: Serializable {
    func serializableMapping() -> Mapping {
        return AutoMapping.mapping(
            for: self, 
            style: .lowercaseSeparatedByUnderScore
        )
    }
}

// Serialize ExampleStruct with auto mapping
let exampleStruct = ExampleStruct()
let jsnObject = exampleStruct.serialize()
/*
 "jsonObject" will be a dictionary with content:
 [
    "string": "string",
    "another_string": "anotherString",
    "int": 1,
    "url": "https://github.com"
 ]
 */

Custom Type Convertible

class CustomClass {
    let string = "string"
    let int = 1
    private var converted: String {
        return "Converted to: \(string), \(int)"
    }
}

extension CustomClass: Convertible {
    func convert() -> Any {
        return converted
    }
}

struct ExampleStruct {
    let customClass = CustomClass()
}

extension ExampleStruct: Serializable {
    func serializableMapping() -> Mapping {
        return AutoMapping.mapping(
            for: self, 
            style: .lowercaseSeparatedByUnderScore
        )
    }
}

// Serialize ExampleStruct
let exampleStruct = ExampleStruct()
let jsonObject = exampleStruct.serialize()
/*
 "jsonObject" will be a dictionary with content:
 [
    "custom_class": "Converted to: string, int"
 ]
 */