Ditto-Swift 1.0.4

Ditto-Swift 1.0.4

测试已测试
Lang语言 SwiftSwift
许可 MIT 协议
发布最后发布2017年8月
SwiftSwift 版本3.0
SPM支持 SPM

Kevin Lin 维护。



  • Kevin Lin

Ditto CI Status

Ditto 允许你将 Swift 对象序列化为与 JSON 兼容的字典。

特性

  • 可自定义的映射。
  • 使用常用映射风格的自动映射。
  • 支持自定义类型转换器。
  • 支持嵌套可序列化。

要求

  • Xcode 8.0+
  • Swift 3.0

使用

CocoaPods

pod 'Ditto-Swift'

Carthage

github "kevin0571/Ditto"

Swift 包管理器

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

概述

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()

自动映射

可用的自动映射风格:lowercaseSeparatedByUnderScorelowercaselowerCamelCaseupperCamelCase

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"
 ]
 */

自定义类型转换器

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"
 ]
 */