alibaba/HandyJSON

Name: HandyJSON

Owner: Alibaba

Description: A handy swift json-object serialization/deserialization library

Created: 2016-09-20 02:31:15.0

Updated: 2018-05-24 15:45:50.0

Pushed: 2018-04-23 09:37:09.0

Homepage:

Size: 435

Language: Swift

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

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 Carthage compatible Cocoapods Version Cocoapods Platform Codecov branch

????
???

??: 581331250

???

Sample Code
Deserialization
s BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!

required init() {}


jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
et object = BasicTypes.deserialize(from: jsonString) {
print(object.int)
print(object.doubleOptional!)
print(object.stringImplicitlyUnwrapped)

Serialization
object = BasicTypes()
ct.int = 1
ct.doubleOptional = 1.1
ct.stringImplicitlyUnwrapped = ?hello"

t(object.toJSON()!) // serialize to dictionary
t(object.toJSONString()!) // serialize to JSON string
t(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string

Content

Features

An overview of types supported can be found at file: BasicTypes.swift

Requirements

Installation

To use with Swift 3.x using >= 1.8.0

To use with Swift 4.0 using == 4.1.1

For Legacy Swift2.x support, take a look at the swift2 branch.

Cocoapods

Add the following line to your Podfile:

'HandyJSON', '~> 4.1.1'

Then, run the following command:

d install
Carthage

You can add a dependency on HandyJSON by adding the following line to your Cartfile:

ub "alibaba/HandyJSON" ~> 4.1.1
Manually

You can integrate HandyJSON into your project manually by doing the following steps:

init && git submodule add https://github.com/alibaba/HandyJSON.git

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.

s BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!

required init() {}


jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
et object = BasicTypes.deserialize(from: jsonString) {
// ?

Support Struct

For struct, since the compiler provide a default empty initializer, we use it for free.

ct BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!


jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
et 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.

 AnimalType: String, HandyJSONEnum {
case Cat = "cat"
case Dog = "dog"
case Bird = "bird"


ct Animal: HandyJSON {
var name: String?
var type: AnimalType?


jsonString = "{\"type\":\"cat\",\"name\":\"Tom\"}"
et 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.

s 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() {}


object = BasicTypes()
ct.intOptional = 1
ct.doubleImplicitlyUnwrapped = 1.1
ct.anyObjectOptional = "StringValue"
ct.arrayInt = [1, 2]
ct.arrayStringOptional = ["a", "b"]
ct.setInt = [1, 2]
ct.dictAnyObject = ["key1": 1, "key2": "stringValue"]
ct.nsNumber = 2
ct.nsString = "nsStringValue"

jsonString = object.toJSONString()!

et object = BasicTypes.deserialize(from: jsonString) {
// ...

Designated Path

HandyJSON supports deserialization from designated path of JSON.

s Cat: HandyJSON {
var id: Int64!
var name: String!

required init() {}


jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"

et 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.

s Component: HandyJSON {
var aInt: Int?
var aString: String?

required init() {}


s Composition: HandyJSON {
var aInt: Int?
var comp1: Component?
var comp2: Component?

required init() {}


jsonString = "{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}"

et composition = Composition.deserialize(from: jsonString) {
print(composition)

Inheritance Object

A subclass need deserialization, it's superclass need to conform to HandyJSON.

s Animal: HandyJSON {
var id: Int?
var color: String?

required init() {}


s Cat: Animal {
var name: String?

required init() {}


jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"

et 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.

s Cat: HandyJSON {
var name: String?
var id: String?

required init() {}


jsonArrayString: String? = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"
et cats = [Cat].deserialize(from: jsonArrayString) {
cats.forEach({ (cat) in
    // ...
})

Mapping From Dictionary

HandyJSON support mapping swift dictionary to model.

dict = [String: Any]()
["doubleOptional"] = 1.1
["stringImplicitlyUnwrapped"] = "hello"
["int"] = 1
et 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.

s 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"
}


jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"

et 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.

s 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() {}


object = ExtendType()
ct.date = Date()
ct.decimal = NSDecimalNumber(string: "1.23423414371298437124391243")
ct.url = URL(string: "https://www.aliyun.com")
ct.data = Data(base64Encoded: "aGVsbG8sIHdvcmxkIQ==")
ct.color = UIColor.blue

t(object.toJSONString()!)
t prints:
"date":"2017-09-11","decimal":"1.23423414371298437124391243","url":"https:\/\/www.aliyun.com","data":"aGVsbG8sIHdvcmxkIQ==","color":"0000FF"}

mappedObject = ExtendType.deserialize(from: object.toJSONString()!)!
t(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.

s NotHandyJSONType {
var dummy: String?


s 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
}


jsonString = "{\"name\":\"cat\",\"id\":\"12345\"}"

et cat = Cat.deserialize(from: jsonString) {
print(cat)

Update Existing Model

HandyJSON support updating an existing model with given json string or dictionary.

s BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!

required init() {}


object = BasicTypes()
ct.int = 1
ct.doubleOptional = 1.1

jsonString = "{\"doubleOptional\":2.2}"
Deserializer.update(object: &object, from: jsonString)
t(object.int)
t(object.doubleOptional)
Supported Property Type

Serialization

The Basics

Now, a class/model which need to serialize to JSON should also conform to HandyJSON protocol.

s BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!

required init() {}


object = BasicTypes()
ct.int = 1
ct.doubleOptional = 1.1
ct.stringImplicitlyUnwrapped = ?hello"

t(object.toJSON()!) // serialize to dictionary
t(object.toJSONString()!) // serialize to JSON string
t(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:

s 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.

s 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:

 EnumType: String {
case type1, type2


s BasicTypes: HandyJSON {
var type: EnumType?

func mapping(mapper: HelpingMapper) {
    mapper <<<
        type <-- EnumTransform()
}

required init() {}


object = BasicTypes()
ct.type = EnumType.type2
t(object.toJSONString()!)
mappedObject = BasicTypes.deserialize(from: object.toJSONString()!)!
t(mappedObject.type)

Otherwise, you should implement your custom mapping function.

 EnumType {
case type1, type2


s 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() {}

License

HandyJSON is released under the Apache License, Version 2.0. See LICENSE for details.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.