ObjectMapper
============
[![CocoaPods](https://img.shields.io/cocoapods/v/ObjectMapper.svg)](https://github.com/tristanhimmelman/ObjectMapper)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Swift Package Manager](https://rawgit.com/jlyonsmith/artwork/master/SwiftPackageManager/swiftpackagemanager-compatible.svg)](https://swift.org/package-manager/)
[![Build Status](https://travis-ci.org/tristanhimmelman/ObjectMapper.svg?branch=master)](https://travis-ci.org/tristanhimmelman/ObjectMapper)
ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from JSON.
- [Features](#features)
- [The Basics](#the-basics)
- [Mapping Nested Objects](#easy-mapping-of-nested-objects)
- [Custom Transformations](#custom-transforms)
- [Subclassing](#subclasses)
- [Generic Objects](#generic-objects)
- [Mapping Context](#mapping-context)
- [ObjectMapper + Alamofire](#objectmapper--alamofire)
- [ObjectMapper + Realm](#objectmapper--realm)
- [Projects using ObjectMapper](#projects-using-objectmapper)
- [To Do](#to-do)
- [Contributing](#contributing)
- [Installation](#installation)
# Features:
- Mapping JSON to objects
- Mapping objects to JSON
- Nested Objects (stand alone, in arrays or in dictionaries)
- Custom transformations during mapping
- Struct support
- [Immutable support](#immutablemappable-protocol)
# The Basics
To support mapping, a class or struct just needs to implement the ```Mappable``` protocol which includes the following functions:
```swift
init?(map: Map)
mutating func mapping(map: Map)
```
ObjectMapper uses the ```<-``` operator to define how each member variable maps to and from JSON.
```swift
class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [Any]?
var dictionary: [String : Any] = [:]
var bestFriend: User? // Nested User object
var friends: [User]? // Array of Users
var birthday: Date?
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
weight <- map["weight"]
array <- map["arr"]
dictionary <- map["dict"]
bestFriend <- map["best_friend"]
friends <- map["friends"]
birthday <- (map["birthday"], DateTransform())
}
}
struct Temperature: Mappable {
var celsius: Double?
var fahrenheit: Double?
init?(map: Map) {
}
mutating func mapping(map: Map) {
celsius <- map["celsius"]
fahrenheit <- map["fahrenheit"]
}
}
```
Once your class implements `Mappable`, ObjectMapper allows you to easily convert to and from JSON.
Convert a JSON string to a model object:
```swift
let user = User(JSONString: JSONString)
```
Convert a model object to a JSON string:
```swift
let JSONString = user.toJSONString(prettyPrint: true)
```
Alternatively, the `Mapper.swift` class can also be used to accomplish the above (it also provides extra functionality for other situations):
```swift
// Convert JSON String to Model
let user = Mapper<User>().map(JSONString: JSONString)
// Create JSON String from Model
let JSONString = Mapper().toJSONString(user, prettyPrint: true)
```
ObjectMapper can map classes composed of the following types:
- `Int`
- `Bool`
- `Double`
- `Float`
- `String`
- `RawRepresentable` (Enums)
- `Array<Any>`
- `Dictionary<String, Any>`
- `Object<T: Mappable>`
- `Array<T: Mappable>`
- `Array<Array<T: Mappable>>`
- `Set<T: Mappable>`
- `Dictionary<String, T: Mappable>`
- `Dictionary<String, Array<T: Mappable>>`
- Optionals of all the above
- Implicitly Unwrapped Optionals of the above
## `Mappable` Protocol
#### `mutating func mapping(map: Map)`
This function is where all mapping definitions should go. When parsing JSON, this function is executed after successful object creation. When generating JSON, it is the only function that is called on the object.
#### `init?(map: Map)`
This failable initializer is used by ObjectMapper for object creation. It can be used by developers to validate JSON prior to object serialization. Returning nil within the function will prevent the mapping from occuring. You can inspect the JSON stored within the `Map` object to do your validation:
```swift
required init?(map: Map){
// check if a required "name" property exists within the JSON.
if map.JSON["name"] == nil {
return nil
}
}
```
## `StaticMappable` Protocol
`StaticMappable` is an alternative to `Mappable`. It provides developers with a static function that is used by ObjectMapper for object initialization instead of `init?(map: Map)`.
Note: `StaticMappable`, like `Mappable`, is a sub protocol of `BaseMappable` which is where the `mapping(map: Map)` function is defined.
#### `static func objectForMapping(map: Map) -> BaseMappable?`
ObjectMapper uses this function to get objects to use for mapping. Developers should return an instance of an object that conforms to `BaseMappable` in this function. This function can also be used to:
- validate JSON prior to object serialization
- provide an existing cached object to be used for mapping
- return an object of another type (which also conforms to `BaseMappable`) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for mapping ([see examples in ClassClusterTests.swift](https://github.com/Hearst-DD/ObjectMapper/blob/master/Tests/ObjectMapperTests/ClassClusterTests.swift#L67))
If you need to implement ObjectMapper in an extension, you will need to adopt this protocol instead of `Mappable`.
## `ImmutableMappable` Protocol
`ImmutableMappable` provides the ability to map immutable properties. This is how `ImmutableMappable` differs from `Mappable`:
<table>
<tr>
<th>ImmutableMappable</th>
<th>Mappable</th>
</tr>
<tr>
<th colspan="2">Properties</th>
</tr>
<tr>
<td>
<pre>
<strong>let</strong> id: Int
<strong>let</strong> name: String?
</pre>
</td>
<td>
<pre>
var id: Int!
var name: String?
</pre>
</td>
</tr>
<tr>
<th colspan="2">JSON -> Model</th>
</tr>
<tr>
<td>
<pre>
init(map: Map) <strong>throws</strong> {
id = <strong>try</strong> map.value("id")
name = <strong>try?</strong> map.value("name")
}
</pre>
</td>
<td>
<pre>
mutating func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
}
</pre>
</td>
</tr>
<tr>
<th colspan="2">Model -> JSON</th>
</tr>
<tr>
<td>
<pre>
func mapping(map: Map) {
id <strong>>>></strong> map["id"]
name <strong>>>></strong> map["name"]
}
</pre>
</td>
<td>
<pre>
mutating func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
}
</pre>
</td>
</tr>
<tr>
<th colspan="2">Initializing</th>
</tr>
<tr>
<td>
<pre>
<strong>try</strong> User(JSONString: JSONString)
</pre>
</td>
<td>
<pre>
User(JSONString: JSONString)
</pre>
</td>
</tr>
</table>
#### `init(map: Map) throws`
This throwable initializer is used to map immutable properties from the given `Map`. Every immutable property should be initialized in this initializer.
This initializer throws an error when:
- `Map` fails to get a value for the given key
- `Map` fails to transform a value using `Transform`
`ImmutableMappable` uses `Map.value(_:using:)` method to get values from the `Map`. This method should be used with the `try` keyword as it is throwable. `Optional` properties can easily be handled using `try?`.
```swift
init(map: Map) throws {
name = try map.value("name") // throws an error when it fails
createdAt = try map.value("createdAt", using: DateTransform()) // throws an error when it fails
updatedAt = try? map.value("updatedAt", using: DateTransform()) // optional
posts = (try? map.value("posts")) ?? [] // option
没有合适的资源?快使用搜索试试~ 我知道了~
swift-ObjectMapper是一个用Swift编写的框架可以轻松地将模型对象转换为JSON和从JSON转换
共68个文件
swift:49个
xcscheme:4个
md:3个
需积分: 35 3 下载量 118 浏览量
2019-08-15
03:30:11
上传
评论
收藏 124KB ZIP 举报
温馨提示
ObjectMapper是一个用Swift编写的框架,它使您可以轻松地将模型对象(类和结构)转换为JSON和从JSON转换
资源推荐
资源详情
资源评论
收起资源包目录
swift-ObjectMapper是一个用Swift编写的框架可以轻松地将模型对象转换为JSON和从JSON转换.zip (68个子文件)
tristanhimmelman-ObjectMapper-19d499c
.gitignore 319B
Package.swift 77B
README.md 17KB
.github
ISSUE_TEMPLATE.md 624B
Package@swift-4.swift 441B
ObjectMapper.podspec 621B
Sources
DateFormatterTransform.swift 2KB
URLTransform.swift 2KB
ToJSON.swift 6KB
TransformOf.swift 2KB
MapError.swift 2KB
DataTransform.swift 2KB
TransformOperators.swift 25KB
Mappable.swift 4KB
EnumTransform.swift 2KB
ImmutableMappable.swift 17KB
Mapper.swift 15KB
ISO8601DateTransform.swift 2KB
IntegerOperators.swift 5KB
FromJSON.swift 8KB
Info.plist 807B
EnumOperators.swift 4KB
ObjectMapper.h 2KB
CodableTransform.swift 2KB
Operators.swift 11KB
ObjectMapper 1B
CustomDateFormatTransform.swift 2KB
Map.swift 7KB
DateTransform.swift 2KB
DictionaryTransform.swift 2KB
TransformType.swift 1KB
HexColorTransform.swift 4KB
NSDecimalNumberTransform.swift 2KB
LICENSE 1KB
ObjectMapper.xcworkspace
contents.xcworkspacedata 158B
xcshareddata
ObjectMapper.xcscmblueprint 2KB
Package@swift-4.2.swift 451B
ObjectMapper.xcodeproj
project.xcworkspace
contents.xcworkspacedata 157B
project.pbxproj 96KB
xcshareddata
xcschemes
ObjectMapper-tvOS.xcscheme 4KB
ObjectMapper-iOS.xcscheme 4KB
ObjectMapper-watchOS.xcscheme 4KB
ObjectMapper-Mac.xcscheme 4KB
README-CN.md 16KB
Tests
Info.plist 733B
ObjectMapperTests
PerformanceTests.swift 5KB
ToObjectTests.swift 6KB
CustomTransformTests.swift 9KB
DictionaryTransformTests.swift 3KB
IgnoreNilTests.swift 2KB
URLTransformTests.swift 2KB
NestedArrayTests.swift 3KB
BasicTypesTestsToJSON.swift 20KB
GenericObjectsTests.swift 5KB
NSDecimalNumberTransformTests.swift 4KB
ClassClusterTests.swift 3KB
CodableTests.swift 3KB
MapContextTests.swift 9KB
NestedKeysTests.swift 16KB
ImmutableTests.swift 20KB
BasicTypesTestsFromJSON.swift 22KB
NullableKeysFromJSONTests.swift 4KB
ObjectMapperTests.swift 20KB
BasicTypes.swift 11KB
DataTransformTests.swift 2KB
MappableTypesWithTransformsTests.swift 11KB
MappableExtensionsTests.swift 3KB
.travis.yml 2KB
共 68 条
- 1
资源评论
weixin_39840650
- 粉丝: 409
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功