测试已测试 | ✗ |
Lang语言 | SwiftSwift |
许可 | MIT 协议 |
发布最后发布 | 2017年8月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✓ |
由 Kevin Lin 维护。
Ditto 允许你将 Swift 对象序列化为与 JSON 兼容的字典。
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()
可用的自动映射风格: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"
]
*/
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"
]
*/