HandyJSON
To deal with crash on iOS 15 beta3 please try version 5.0.4-beta
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.
Sample Code
Deserialization
Serialization
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
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/5.1 ( Xcode 10.2+/11.0+ ), version == 5.0.2
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.
Cocoapods
Add the following line to your Podfile
:
pod 'HandyJSON', '~> 5.0.2'
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.2
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 addHandyJSON
as a submodule:
git init && git submodule add https://github.com/alibaba/HandyJSON.git
-
Open the new
HandyJSON
folder, drag theHandyJSON.xcodeproj
into theProject Navigator
of your project. -
Select your application project in the
Project Navigator
, open theGeneral
panel in the right window. -
Click on the
+
button under theEmbedded 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.
Support Struct
For struct, since the compiler provide a default empty initializer, we use it for free.
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.
Optional/ImplicitlyUnwrappedOptional/Collections/...
'HandyJSON' support classes/structs composed of optional
, implicitlyUnwrappedOptional
, array
, dictionary
, objective-c base type
, nested type
etc. properties.
Designated Path
HandyJSON
supports deserialization from designated path of JSON.
Composition Object
Notice that all the properties of a class/struct need to deserialized should be type conformed to HandyJSON
.
Inheritance Object
A subclass need deserialization, it's superclass need to conform to HandyJSON
.
JSON Array
If the first level of a JSON text is an array, we turn it to objects array.
Mapping From Dictionary
HandyJSON
support mapping swift dictionary to model.
Custom Mapping
HandyJSON
let you customize the key mapping to JSON fields, or parsing method of any property. All you need to do is implementing an optional mapping
function, do things in it.
We bring the transformer from ObjectMapper
. If you are familiar with it, it’s almost the same here.
Date/Data/URL/Decimal/Color
HandyJSON
prepare some useful transformer for some none-basic type.
Exclude Property
If any non-basic property of a class/struct could not conform to HandyJSON
/HandyJSONEnum
or you just do not want to do the deserialization with it, you should exclude it in the mapping function.
Update Existing Model
HandyJSON
support updating an existing model with given json string or dictionary.
Supported Property Type
-
Int
/Bool
/Double
/Float
/String
/NSNumber
/NSString
-
RawRepresentable
enum -
NSArray/NSDictionary
-
Int8/Int16/Int32/Int64
/UInt8/UInt16/UInt23/UInt64
-
Optional<T>/ImplicitUnwrappedOptional<T>
// T is one of the above types -
Array<T>
// T is one of the above types -
Dictionary<String, T>
// T is one of the above types -
Nested of aboves
Serialization
The Basics
Now, a class/model which need to serialize to JSON should also conform to HandyJSON
protocol.
Mapping And Excluding
It’s all like what we do on deserialization. A property which is excluded, it will not take part in neither deserialization nor serialization. And the mapper items define both the deserializing rules and serializing rules. Refer to the usage above.
FAQ
Q: Why the mapping function is not working in the inheritance object?
A: For some reason, you should define an empty mapping function in the super class(the root class if more than one layer), and override it in the subclass.
It's the same with didFinishMapping
function.
Q: Why my didSet/willSet is not working?
A: Since HandyJSON
assign properties by writing value to memory directly, it doesn't trigger any observing function. You need to call the didSet/willSet
logic explicitly after/before the deserialization.
But since version 1.8.0
, HandyJSON
handle dynamic properties by the KVC
mechanism which will trigger the KVO
. That means, if you do really need the didSet/willSet
, you can define your model like follow:
In this situation, NSObject
and dynamic
are both needed.
And in versions since 1.8.0
, HandyJSON
offer a didFinishMapping
function to allow you to fill some observing logic.
It may help.
Q: How to support Enum property?
It your enum conform to RawRepresentable
protocol, please look into Support Enum Property. Or use the EnumTransform
:
Otherwise, you should implement your custom mapping function.
Credit
- reflection: After the first version which used the swift mirror mechanism, HandyJSON had imported the reflection library and rewrote some code for class properties inspecting.
- ObjectMapper: To make HandyJSON more compatible with the general style, the Mapper function support Transform which designed by ObjectMapper. And we import some testcases from ObjectMapper.
License
HandyJSON is released under the Apache License, Version 2.0. See LICENSE for details.