HandyJSON
A handy swift json-object serialization/deserialization library
Install / Use
/learn @alibaba/HandyJSONREADME
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.
中文文档
交流群
群号: 581331250

Sample Code
Deserialization
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
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
-
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,cdinto your top-level project directory, and addHandyJSONas a submodule:
git init && git submodule add https://github.com/alibaba/HandyJSON.git
-
Open the new
HandyJSONfolder, drag theHandyJSON.xcodeprojinto theProject Navigatorof your project. -
Select your application project in the
Project Navigator, open theGeneralpanel in the right window. -
Click on the
+button under theEmbedded Binariessection. -
You will see two different
HandyJSON.xcodeprojfolders 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.frameworkwhich 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.
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.
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.
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.
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.nsNumber = 2
object.nsString = "nsStringValue"
let jsonString = object.toJSONString()!
if let object = BasicTypes.deserialize(from: jsonString) {
// ...
}
Designated Path
HandyJSON supports deserialization from designated path of JSON.
class Cat: HandyJSON {
var id: Int64!
var name: String!
required init() {}
}
let jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"
if let cat = Cat.deserialize(from: jsonString, designatedPath: "data.cat") {
print(cat.name)
}
Composition Object
Notice that all the properties of a class/struct need to deserialized should be type conformed to HandyJSON.
class Component: HandyJSON {
var aInt: Int?
var aString: String?
required init() {}
}
class Composition: HandyJSON {
var aInt: Int?
var comp1: Component?
var comp2: Component?
required init() {}
}
let jsonString = "{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}"
if let composition = Composition.deserialize(from: jsonString) {
print(composition)
}
Inheritance Object
A subclass need deserialization, it's superclass need to conform to HandyJSON.
class Animal: HandyJSON {
var id: Int?
var color: String?
required init() {}
}
class Cat: Animal {
var name: String?
required init() {}
}
let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"
if let cat = Cat.deserialize(from: jsonString) {
print(cat)
}
JSON Array
If the first level of a JSON text is an array, we turn it to objects array.
class Cat: HandyJSON {
var name: String?
var id: String?
required init() {}
}
let jsonArrayString: String? = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"
if let cats = [Cat].deserialize(from: js
Related Skills
node-connect
335.9kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
82.7kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
335.9kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
82.7kCommit, push, and open a PR
