Top Related Projects
The better way to deal with JSON data in Swift.
Simple JSON Object mapping written in Swift
Type-erased wrappers for Encodable, Decodable, and Codable values
Plugin and runtime library for using protobuf with Swift
Quick Overview
HandyJSON is a Swift library that provides an easy way to convert Swift objects to and from JSON. It supports automatic coding/decoding of most Swift types and allows for custom transformations. HandyJSON is designed to be simple to use and doesn't require any additional code generation steps.
Pros
- Easy to use with minimal setup required
- Supports automatic coding/decoding for most Swift types
- Allows for custom transformations and property mapping
- No need for external code generation tools
Cons
- Not as performant as some other JSON parsing libraries
- Lacks support for certain advanced features like conditional coding
- May not be suitable for extremely complex JSON structures
- Less actively maintained compared to some alternatives
Code Examples
- Basic model definition and JSON parsing:
import HandyJSON
struct User: HandyJSON {
var id: Int?
var name: String?
}
let jsonString = "{\"id\":1,\"name\":\"John\"}"
if let user = User.deserialize(from: jsonString) {
print(user.name ?? "") // Output: John
}
- Custom property mapping:
struct Book: HandyJSON {
var id: Int?
var title: String?
var authorName: String?
mutating func mapping(mapper: HelpingMapper) {
mapper <<< self.authorName <-- "author.name"
}
}
let jsonString = "{\"id\":1,\"title\":\"Swift Programming\",\"author\":{\"name\":\"John Doe\"}}"
if let book = Book.deserialize(from: jsonString) {
print(book.authorName ?? "") // Output: John Doe
}
- Custom transformation:
struct Date: HandyJSON {
var timestamp: TimeInterval?
mutating func mapping(mapper: HelpingMapper) {
mapper <<< self.timestamp <-- TransformOf<TimeInterval, String>(fromJSON: { (string) -> TimeInterval? in
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: string!)?.timeIntervalSince1970
}, toJSON: { (timestamp) -> String? in
let date = Date(timeIntervalSince1970: timestamp!)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
})
}
}
let jsonString = "{\"timestamp\":\"2023-05-01\"}"
if let date = Date.deserialize(from: jsonString) {
print(date.timestamp ?? 0) // Output: 1682899200.0
}
Getting Started
-
Add HandyJSON to your project using Swift Package Manager:
dependencies: [ .package(url: "https://github.com/alibaba/HandyJSON.git", from: "5.0.0") ]
-
Import HandyJSON in your Swift file:
import HandyJSON
-
Make your model conform to the
HandyJSON
protocol:struct MyModel: HandyJSON { var property1: String? var property2: Int? }
-
Use the
deserialize(from:)
method to parse JSON:let jsonString = "{\"property1\":\"value\",\"property2\":42}" if let model = MyModel.deserialize(from: jsonString) { print(model.property1 ?? "") print(model.property2 ?? 0) }
Competitor Comparisons
The better way to deal with JSON data in Swift.
Pros of SwiftyJSON
- More mature and widely adopted project with a larger community
- Supports both reading and writing JSON data
- Offers a more flexible and chainable syntax for JSON manipulation
Cons of SwiftyJSON
- Requires more manual type casting and error handling
- Slightly more verbose syntax for simple operations
- May have a steeper learning curve for beginners
Code Comparison
SwiftyJSON:
let json = JSON(data: dataFromNetworking)
if let name = json["user"]["name"].string {
print(name)
}
HandyJSON:
struct User: HandyJSON {
var name: String?
}
let user = User.deserialize(from: jsonString)
print(user?.name ?? "")
Key Differences
- HandyJSON focuses on object mapping, while SwiftyJSON provides a more general-purpose JSON handling approach
- SwiftyJSON offers more flexibility in working with JSON data, but HandyJSON provides a simpler API for object serialization and deserialization
- HandyJSON leverages Swift's Codable protocol, making it more integrated with Swift's native features
- SwiftyJSON has better support for complex JSON structures and nested data
Use Cases
- Choose SwiftyJSON for projects requiring complex JSON manipulation and flexibility
- Opt for HandyJSON when working primarily with object mapping and simpler JSON structures
Both libraries have their strengths, and the choice depends on specific project requirements and developer preferences.
Simple JSON Object mapping written in Swift
Pros of ObjectMapper
- More mature and widely adopted in the Swift community
- Supports custom transformations for complex data types
- Offers better performance for large datasets
Cons of ObjectMapper
- Requires manual implementation of
Mappable
protocol - More verbose syntax for mapping properties
- Slightly steeper learning curve for beginners
Code Comparison
ObjectMapper:
class User: Mappable {
var name: String?
var age: Int?
required init?(map: Map) {}
func mapping(map: Map) {
name <- map["name"]
age <- map["age"]
}
}
HandyJSON:
class User: HandyJSON {
var name: String?
var age: Int?
required init() {}
}
HandyJSON offers a more concise syntax for simple models, requiring less boilerplate code. However, ObjectMapper provides more flexibility for complex mapping scenarios and custom transformations.
Both libraries aim to simplify JSON parsing in Swift, but they differ in their approach and feature set. ObjectMapper is more established and feature-rich, while HandyJSON focuses on simplicity and ease of use. The choice between them depends on project requirements, performance needs, and developer preferences.
Type-erased wrappers for Encodable, Decodable, and Codable values
Pros of AnyCodable
- Focused specifically on encoding and decoding
Any
type - Lightweight and easy to integrate
- Supports both Codable and NSCoding protocols
Cons of AnyCodable
- Limited to handling
Any
type, not a full JSON parsing solution - Requires more manual work for complex JSON structures
- Less feature-rich compared to HandyJSON
Code Comparison
AnyCodable:
let value: Any = ["key": "value"]
let data = try JSONEncoder().encode(AnyCodable(value))
let decoded = try JSONDecoder().decode(AnyCodable.self, from: data)
HandyJSON:
struct Model: HandyJSON {
var key: String?
}
let jsonString = "{\"key\":\"value\"}"
let model = Model.deserialize(from: jsonString)
Key Differences
- HandyJSON offers a more comprehensive JSON parsing solution
- AnyCodable focuses on handling the
Any
type in Codable contexts - HandyJSON provides more automatic parsing and mapping features
- AnyCodable integrates seamlessly with Swift's Codable protocol
- HandyJSON has a larger feature set but may be overkill for simpler use cases
Both libraries serve different purposes, with AnyCodable being more specialized and HandyJSON offering a broader range of JSON handling capabilities.
Plugin and runtime library for using protobuf with Swift
Pros of swift-protobuf
- Officially supported by Apple, ensuring compatibility with Swift ecosystem
- Optimized for performance and efficiency in serialization/deserialization
- Strong type safety and compile-time checks
Cons of swift-protobuf
- Requires .proto files and protobuf compiler, adding complexity to the workflow
- Less flexible for dynamic JSON structures or custom mapping
Code Comparison
HandyJSON:
struct Person: HandyJSON {
var name: String?
var age: Int?
}
let jsonString = "{\"name\":\"Bob\",\"age\":28}"
if let person = Person.deserialize(from: jsonString) {
print(person.name ?? "", person.age ?? 0)
}
swift-protobuf:
// Assuming a .proto file defining Person message
let jsonString = "{\"name\":\"Bob\",\"age\":28}"
var person = Person()
try person.merge(jsonString: jsonString)
print(person.name, person.age)
HandyJSON offers a simpler setup for JSON parsing without additional files or compilers. It's more flexible for dynamic JSON structures but lacks the performance optimizations and strong type safety of swift-protobuf. swift-protobuf, while requiring more setup, provides better performance and type safety, making it suitable for larger projects with well-defined data structures.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
,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.
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: jsonArrayString) {
cats.forEach({ (cat) in
// ...
})
}
Mapping From Dictionary
HandyJSON
support mapping swift dictionary to model.
var dict = [String: Any]()
dict["doubleOptional"] = 1.1
dict["stringImplicitlyUnwrapped"] = "hello"
dict["int"] = 1
if let object = BasicTypes.deserialize(from: dict) {
// ...
}
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.
class Cat: HandyJSON {
var id: Int64!
var name: String!
var parent: (String, String)?
var friendName: String?
required init() {}
func mapping(mapper: HelpingMapper) {
// specify 'cat_id' field in json map to 'id' property in object
mapper <<<
self.id <-- "cat_id"
// specify 'parent' field in json parse as following to 'parent' property in object
mapper <<<
self.parent <-- TransformOf<(String, String), String>(fromJSON: { (rawString) -> (String, String)? in
if let parentNames = rawString?.characters.split(separator: "/").map(String.init) {
return (parentNames[0], parentNames[1])
}
return nil
}, toJSON: { (tuple) -> String? in
if let _tuple = tuple {
return "\(_tuple.0)/\(_tuple.1)"
}
return nil
})
// specify 'friend.name' path field in json map to 'friendName' property
mapper <<<
self.friendName <-- "friend.name"
}
}
let jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"
if let cat = Cat.deserialize(from: jsonString) {
print(cat.id)
print(cat.parent)
print(cat.friendName)
}
Date/Data/URL/Decimal/Color
HandyJSON
prepare some useful transformer for some none-basic type.
class ExtendType: HandyJSON {
var date: Date?
var decimal: NSDecimalNumber?
var url: URL?
var data: Data?
var color: UIColor?
func mapping(mapper: HelpingMapper) {
mapper <<<
date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
mapper <<<
decimal <-- NSDecimalNumberTransform()
mapper <<<
url <-- URLTransform(shouldEncodeURLString: false)
mapper <<<
data <-- DataTransform()
mapper <<<
color <-- HexColorTransform()
}
public required init() {}
}
let object = ExtendType()
object.date = Date()
object.decimal = NSDecimalNumber(string: "1.23423414371298437124391243")
object.url = URL(string: "https://www.aliyun.com")
object.data = Data(base64Encoded: "aGVsbG8sIHdvcmxkIQ==")
object.color = UIColor.blue
print(object.toJSONString()!)
// it prints:
// {"date":"2017-09-11","decimal":"1.23423414371298437124391243","url":"https:\/\/www.aliyun.com","data":"aGVsbG8sIHdvcmxkIQ==","color":"0000FF"}
let mappedObject = ExtendType.deserialize(from: object.toJSONString()!)!
print(mappedObject.date)
...
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.
class NotHandyJSONType {
var dummy: String?
}
class Cat: HandyJSON {
var id: Int64!
var name: String!
var notHandyJSONTypeProperty: NotHandyJSONType?
var basicTypeButNotWantedProperty: String?
required init() {}
func mapping(mapper: HelpingMapper) {
mapper >>> self.notHandyJSONTypeProperty
mapper >>> self.basicTypeButNotWantedProperty
}
}
let jsonString = "{\"name\":\"cat\",\"id\":\"12345\"}"
if let cat = Cat.deserialize(from: jsonString) {
print(cat)
}
Update Existing Model
HandyJSON
support updating an existing model with given json string or dictionary.
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
required init() {}
}
var object = BasicTypes()
object.int = 1
object.doubleOptional = 1.1
let jsonString = "{\"doubleOptional\":2.2}"
JSONDeserializer.update(object: &object, from: jsonString)
print(object.int)
print(object.doubleOptional)
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.
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
required init() {}
}
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
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:
class BasicTypes: NSObject, HandyJSON {
dynamic var int: Int = 0 {
didSet {
print("oldValue: ", oldValue)
}
willSet {
print("newValue: ", newValue)
}
}
public override required init() {}
}
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.
class BasicTypes: HandyJSON {
var int: Int?
required init() {}
func didFinishMapping() {
print("you can fill some observing logic here")
}
}
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
:
enum EnumType: String {
case type1, type2
}
class BasicTypes: HandyJSON {
var type: EnumType?
func mapping(mapper: HelpingMapper) {
mapper <<<
type <-- EnumTransform()
}
required init() {}
}
let object = BasicTypes()
object.type = EnumType.type2
print(object.toJSONString()!)
let mappedObject = BasicTypes.deserialize(from: object.toJSONString()!)!
print(mappedObject.type)
Otherwise, you should implement your custom mapping function.
enum EnumType {
case type1, type2
}
class BasicTypes: HandyJSON {
var type: EnumType?
func mapping(mapper: HelpingMapper) {
mapper <<<
type <-- TransformOf<EnumType, String>(fromJSON: { (rawString) -> EnumType? in
if let _str = rawString {
switch (_str) {
case "type1":
return EnumType.type1
case "type2":
return EnumType.type2
default:
return nil
}
}
return nil
}, toJSON: { (enumType) -> String? in
if let _type = enumType {
switch (_type) {
case EnumType.type1:
return "type1"
case EnumType.type2:
return "type2"
}
}
return nil
})
}
required init() {}
}
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.
Top Related Projects
The better way to deal with JSON data in Swift.
Simple JSON Object mapping written in Swift
Type-erased wrappers for Encodable, Decodable, and Codable values
Plugin and runtime library for using protobuf with Swift
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot