# HandyJSON
HandyJSON is a framework written in Swift which to make converting model objects( **pure classes/structs** ) to and from JSON easy on iOS.
Compared with others, the most significant feature of HandyJSON is that it does not require the objects inherit from NSObject(**not using KVC but reflection**), neither implements a 'mapping' function(**writing value to memory directly to achieve property assignment**).
HandyJSON is totally depend on the memory layout rules infered from Swift runtime code. We are watching it and will follow every bit if it changes.
[![Build Status](https://travis-ci.org/alibaba/HandyJSON.svg?branch=master)](https://travis-ci.org/alibaba/HandyJSON)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Cocoapods Version](https://img.shields.io/cocoapods/v/HandyJSON.svg?style=flat)](http://cocoadocs.org/docsets/HandyJSON)
[![Cocoapods Platform](https://img.shields.io/cocoapods/p/HandyJSON.svg?style=flat)](http://cocoadocs.org/docsets/HandyJSON)
[![Codecov branch](https://img.shields.io/codecov/c/github/alibaba/HandyJSON/master.svg?style=flat)](https://codecov.io/gh/alibaba/HandyJSON/branch/master)
## [中文文档](./README_cn.md)
## 交流群
群号: 581331250
![交流群](qq_group.png)
## Sample Code
### Deserialization
```swift
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
required init() {}
}
let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
print(object.int)
print(object.doubleOptional!)
print(object.stringImplicitlyUnwrapped)
}
```
### Serialization
```swift
let object = BasicTypes()
object.int = 1
object.doubleOptional = 1.1
object.stringImplicitlyUnwrapped = “hello"
print(object.toJSON()!) // serialize to dictionary
print(object.toJSONString()!) // serialize to JSON string
print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string
```
# Content
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Cocoapods](#cocoapods)
- [Carthage](#carthage)
- [Manually](#manually)
- [Deserialization](#deserialization)
- [The Basics](#the-basics)
- [Support Struct](#support-struct)
- [Support Enum Property](#support-enum-property)
- [Optional/ImplicitlyUnwrappedOptional/Collections/...](#optionalimplicitlyunwrappedoptionalcollections)
- [Designated Path](#designated-path)
- [Composition Object](#composition-object)
- [Inheritance Object](#inheritance-object)
- [JSON Array](#json-array)
- [Mapping From Dictionary](#mapping-from-dictionary)
- [Custom Mapping](#custom-mapping)
- [Date/Data/URL/Decimal/Color](#datedataurldecimalcolor)
- [Exclude Property](#exclude-property)
- [Update Existing Model](#update-existing-model)
- [Supported Property Type](#supported-property-type)
- [Serialization](#serialization)
- [The Basics](#the-basics)
- [Mapping And Excluding](#mapping-and-excluding)
- [FAQ](#faq)
- [To Do](#to-do)
# Features
* Serialize/Deserialize Object/JSON to/From JSON/Object
* Naturally use object property name for mapping, no need to specify a mapping relationship
* Support almost all types in Swift, including enum
* Support struct
* Custom transformations
* Type-Adaption, such as string json field maps to int property, int json field maps to string property
An overview of types supported can be found at file: [BasicTypes.swift](./HandyJSONTest/BasicTypes.swift)
# Requirements
* iOS 8.0+/OSX 10.9+/watchOS 2.0+/tvOS 9.0+
* Swift 3.0+ / Swift 4.0+ / Swift 5.0+
# Installation
**To use with Swift 5.0 ( Xcode 10.2 ), version == 5.0.0**
**To use with Swift 4.2 ( Xcode 10 ), version == 4.2.0**
**To use with Swift 4.0, version >= 4.1.1**
**To use with Swift 3.x, version >= 1.8.0**
For Legacy Swift2.x support, take a look at the [swift2 branch](https://github.com/alibaba/HandyJSON/tree/master_for_swift_2x).
## Cocoapods
Add the following line to your `Podfile`:
```
pod 'HandyJSON', '~> 5.0.0'
```
Then, run the following command:
```
$ pod install
```
## Carthage
You can add a dependency on `HandyJSON` by adding the following line to your `Cartfile`:
```
github "alibaba/HandyJSON" ~> 5.0.0
```
## Manually
You can integrate `HandyJSON` into your project manually by doing the following steps:
* Open up `Terminal`, `cd` into your top-level project directory, and add `HandyJSON` as a submodule:
```
git init && git submodule add https://github.com/alibaba/HandyJSON.git
```
* Open the new `HandyJSON` folder, drag the `HandyJSON.xcodeproj` into the `Project Navigator` of your project.
* Select your application project in the `Project Navigator`, open the `General` panel in the right window.
* Click on the `+` button under the `Embedded Binaries` section.
* You will see two different `HandyJSON.xcodeproj` folders each with four different versions of the HandyJSON.framework nested inside a Products folder.
> It does not matter which Products folder you choose from, but it does matter which HandyJSON.framework you choose.
* Select one of the four `HandyJSON.framework` which matches the platform your Application should run on.
* Congratulations!
# Deserialization
## The Basics
To support deserialization from JSON, a class/struct need to conform to 'HandyJSON' protocol. It's truly protocol, not some class inherited from NSObject.
To conform to 'HandyJSON', a class need to implement an empty initializer.
```swift
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
required init() {}
}
let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
// …
}
```
## Support Struct
For struct, since the compiler provide a default empty initializer, we use it for free.
```swift
struct BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
}
let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
// …
}
```
But also notice that, if you have a designated initializer to override the default one in the struct, you should explicitly declare an empty one(no `required` modifier need).
## Support Enum Property
To be convertable, An `enum` must conform to `HandyJSONEnum` protocol. Nothing special need to do now.
```swift
enum AnimalType: String, HandyJSONEnum {
case Cat = "cat"
case Dog = "dog"
case Bird = "bird"
}
struct Animal: HandyJSON {
var name: String?
var type: AnimalType?
}
let jsonString = "{\"type\":\"cat\",\"name\":\"Tom\"}"
if let animal = Animal.deserialize(from: jsonString) {
print(animal.type?.rawValue)
}
```
## Optional/ImplicitlyUnwrappedOptional/Collections/...
'HandyJSON' support classes/structs composed of `optional`, `implicitlyUnwrappedOptional`, `array`, `dictionary`, `objective-c base type`, `nested type` etc. properties.
```swift
class BasicTypes: HandyJSON {
var bool: Bool = true
var intOptional: Int?
var doubleImplicitlyUnwrapped: Double!
var anyObjectOptional: Any?
var arrayInt: Array<Int> = []
var arrayStringOptional: Array<String>?
var setInt: Set<Int>?
var dictAnyObject: Dictionary<String, Any> = [:]
var nsNumber = 2
var nsString: NSString?
required init() {}
}
let object = BasicTypes()
object.intOptional = 1
object.doubleImplicitlyUnwrapped = 1.1
object.anyObjectOptional = "StringValue"
object.arrayInt = [1, 2]
object.arrayStringOptional = ["a", "b"]
object.setInt = [1, 2]
object.dictAnyObject = ["key1": 1, "key2": "stringValue"]
object.n
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
一个使用百度AI的开放平台,它读取剪贴板中的图片,然后进行OCR (136个子文件)
CutOCR.entitlements 365B
.gitignore 2KB
HandyJSON.h 1002B
HandyJSON-umbrella.h 332B
Pods-CutOCR-umbrella.h 314B
Alamofire-umbrella.h 310B
Contents.json 1KB
Contents.json 1KB
Contents.json 62B
LICENSE 3KB
LICENSE 1KB
LICENSE 1KB
Pods-CutOCR-dummy.m 126B
HandyJSON-dummy.m 122B
Alamofire-dummy.m 122B
Pods-CutOCR-acknowledgements.markdown 4KB
README.md 19KB
README.md 14KB
Pods-CutOCR.modulemap 112B
Alamofire.modulemap 108B
HandyJSON.modulemap 108B
project.pbxproj 71KB
project.pbxproj 27KB
HandyJSON-prefix.pch 195B
Alamofire-prefix.pch 195B
Pods-CutOCR-acknowledgements.plist 5KB
Info.plist 1KB
Alamofire-Info.plist 828B
HandyJSON-Info.plist 828B
Pods-CutOCR-Info.plist 828B
IDEWorkspaceChecks.plist 238B
IDEWorkspaceChecks.plist 238B
512@2x.png 117KB
256@2x.png 53KB
512.png 53KB
256.png 24KB
128@2x.png 24KB
128.png 11KB
32@2x.png 5KB
16@2x.png 2KB
32.png 2KB
naiping@2x.png 1KB
naiping@2x-1.png 940B
naiping.png 938B
16.png 739B
naiping-1.png 628B
Podfile 104B
Pods-CutOCR-frameworks.sh 8KB
Main.storyboard 10KB
Request.swift 62KB
Session.swift 57KB
EventMonitor.swift 41KB
URLEncodedFormEncoder.swift 40KB
ResponseSerialization.swift 37KB
AFError.swift 36KB
ServerTrustEvaluation.swift 29KB
MultipartFormData.swift 21KB
RetryPolicy.swift 21KB
Response.swift 19KB
HTTPHeaders.swift 15KB
SessionDelegate.swift 14KB
ParameterEncoding.swift 13KB
Metadata.swift 11KB
NetworkReachabilityManager.swift 11KB
ExtendCustomModelType.swift 10KB
Validation.swift 10KB
RequestInterceptor.swift 9KB
HelpingMapper.swift 8KB
Deserializer.swift 8KB
ParameterEncoder.swift 8KB
BuiltInBasicType.swift 7KB
Notifications.swift 6KB
RequestTaskMap.swift 6KB
ContextDescriptorType.swift 6KB
Protector.swift 5KB
Result+Alamofire.swift 4KB
RedirectHandler.swift 4KB
CachedResponseHandler.swift 4KB
URLConvertible+URLRequestConvertible.swift 4KB
MultipartUpload.swift 3KB
HexColorTransform.swift 3KB
Measuable.swift 3KB
AnyExtensions.swift 3KB
Serializer.swift 3KB
FieldDescriptor.swift 3KB
OperationQueue+Alamofire.swift 2KB
AlamofireExtended.swift 2KB
HTTPMethod.swift 2KB
URLTransform.swift 2KB
Properties.swift 2KB
AppDelegate.swift 2KB
OtherExtension.swift 2KB
BuiltInBridgeType.swift 2KB
NSDecimalNumberTransform.swift 2KB
DateFormatterTransform.swift 2KB
DateTransform.swift 2KB
TransformOf.swift 2KB
URLSessionConfiguration+Alamofire.swift 2KB
DataTransform.swift 2KB
HttpClient.swift 2KB
共 136 条
- 1
- 2
资源评论
Java程序员-张凯
- 粉丝: 1w+
- 资源: 6713
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功