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
classBasicTypes:HandyJSON{varint:Int=2vardoubleOptional:Double?varstringImplicitlyUnwrapped:String!requiredinit(){}}letjsonString="{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"iflet object =BasicTypes.deserialize(from: jsonString){print(object.int)print(object.doubleOptional!)print(object.stringImplicitlyUnwrapped)}letobject=BasicTypes()
object.int =1
object.doubleOptional =1.1
object.stringImplicitlyUnwrapped = “hello"print(object.toJSON()!) // serialize to dictionaryprint(object.toJSONString()!) // serialize to JSON stringprint(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON stringSerialize/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
iOS 8.0+/OSX 10.9+/watchOS 2.0+/tvOS 9.0+
Swift 3.0+ / Swift 4.0+ / Swift 5.0+
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.
Add the following line to your Podfile:
pod 'HandyJSON', '~> 5.0.2'
Then, run the following command:
$ pod install
You can add a dependency on HandyJSON by adding the following line to your Cartfile:
github "alibaba/HandyJSON" ~> 5.0.2
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!
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.
classBasicTypes:HandyJSON{varint:Int=2vardoubleOptional:Double?varstringImplicitlyUnwrapped:String!requiredinit(){}}letjsonString="{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"iflet object =BasicTypes.deserialize(from: jsonString){
// …
}For struct, since the compiler provide a default empty initializer, we use it for free.
structBasicTypes:HandyJSON{varint:Int=2vardoubleOptional:Double?varstringImplicitlyUnwrapped:String!}letjsonString="{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"iflet 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).
To be convertable, An enum must conform to HandyJSONEnum protocol. Nothing special need to do now.
enumAnimalType:String,HandyJSONEnum{case Cat ="cat"case Dog ="dog"case Bird ="bird"}structAnimal:HandyJSON{varname:String?vartype:AnimalType?}letjsonString="{\"type\":\"cat\",\"name\":\"Tom\"}"iflet animal =Animal.deserialize(from: jsonString){print(animal.type?.rawValue)}'HandyJSON' support classes/structs composed of optional, implicitlyUnwrappedOptional, array, dictionary, objective-c base type, nested type etc. properties.
classBasicTypes:HandyJSON{varbool:Bool=truevarintOptional:Int?vardoubleImplicitlyUnwrapped:Double!varanyObjectOptional:Any?vararrayInt:Array<Int>=[]vararrayStringOptional:Array<String>?varsetInt:Set<Int>?vardictAnyObject:Dictionary<String,Any>=[:]varnsNumber=2varnsString:NSString?requiredinit(){}}letobject=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"letjsonString= object.toJSONString()!
iflet object =BasicTypes.deserialize(from: jsonString){
// ...
}HandyJSON supports deserialization from designated path of JSON.
classCat:HandyJSON{varid:Int64!varname:String!requiredinit(){}}letjsonString="{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"iflet cat =Cat.deserialize(from: jsonString, designatedPath:"data.cat"){print(cat.name)}Notice that all the properties of a class/struct need to deserialized should be type conformed to HandyJSON.
classComponent:HandyJSON{varaInt:Int?varaString:String?requiredinit(){}}classComposition:HandyJSON{varaInt:Int?varcomp1:Component?varcomp2:Component?requiredinit(){}}letjsonString="{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}"iflet composition =Composition.deserialize(from: jsonString){print(composition)}A subclass need deserialization, it's superclass need to conform to HandyJSON.
classAnimal:HandyJSON{varid:Int?varcolor:String?requiredinit(){}}classCat:Animal{varname:String?requiredinit(){}}letjsonString="{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"iflet cat =Cat.deserialize(from: jsonString){print(cat)}If the first level of a JSON text is an array, we turn it to objects array.
classCat:HandyJSON{varname:String?varid:String?requiredinit(){}}letjsonArrayString:String?="[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"iflet cats =[Cat].deserialize(from: jsonArrayString){
cats.forEach({(cat)in
// ...
})}HandyJSON support mapping swift dictionary to model.
vardict=[String: Any]()dict["doubleOptional"]=1.1dict["stringImplicitlyUnwrapped"]="hello"dict["int"]=1iflet object =BasicTypes.deserialize(from: dict){
// ...
}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.
classCat:HandyJSON{varid:Int64!varname:String!varparent:(String,String)?varfriendName:String?requiredinit(){}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)?iniflet parentNames = rawString?.characters.split(separator:"/").map(String.init){return(parentNames[0],parentNames[1])}returnnil}, toJSON:{(tuple)->String?iniflet _tuple = tuple {return"\(_tuple.0)/\(_tuple.1)"}returnnil})
// specify 'friend.name' path field in json map to 'friendName' property
mapper <<<self.friendName <--"friend.name"}}letjsonString="{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"iflet cat =Cat.deserialize(from: jsonString){print(cat.id)print(cat.parent)print(cat.friendName)}HandyJSON prepare some useful transformer for some none-basic type.
classExtendType:HandyJSON{vardate:Date?vardecimal:NSDecimalNumber?varurl:URL?vardata:Data?varcolor: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()}publicrequiredinit(){}}letobject=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"}
letmappedObject=ExtendType.deserialize(from: object.toJSONString()!)!
print(mappedObject.date)...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.
classNotHandyJSONType{vardummy:String?}classCat:HandyJSON{varid:Int64!varname:String!varnotHandyJSONTypeProperty:NotHandyJSONType?varbasicTypeButNotWantedProperty:String?requiredinit(){}func mapping(mapper:HelpingMapper){
mapper >>>self.notHandyJSONTypeProperty
mapper >>>self.basicTypeButNotWantedProperty
}}letjsonString="{\"name\":\"cat\",\"id\":\"12345\"}"iflet cat =Cat.deserialize(from: jsonString){print(cat)}HandyJSON support updating an existing model with given json string or dictionary.
classBasicTypes:HandyJSON{varint:Int=2vardoubleOptional:Double?varstringImplicitlyUnwrapped:String!requiredinit(){}}varobject=BasicTypes()
object.int =1
object.doubleOptional =1.1letjsonString="{\"doubleOptional\":2.2}"JSONDeserializer.update(object:&object, from: jsonString)print(object.int)print(object.doubleOptional)Int/Bool/Double/Float/String/NSNumber/NSStringRawRepresentableenumNSArray/NSDictionaryInt8/Int16/Int32/Int64/UInt8/UInt16/UInt23/UInt64Optional<T>/ImplicitUnwrappedOptional<T>// T is one of the above typesArray<T>// T is one of the above typesDictionary<String, T>// T is one of the above typesNested of aboves
Now, a class/model which need to serialize to JSON should also conform to HandyJSON protocol.
classBasicTypes:HandyJSON{varint:Int=2vardoubleOptional:Double?varstringImplicitlyUnwrapped:String!requiredinit(){}}letobject=BasicTypes()
object.int =1
object.doubleOptional =1.1
object.stringImplicitlyUnwrapped = “hello"print(object.toJSON()!) // serialize to dictionaryprint(object.toJSONString()!) // serialize to JSON stringprint(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON stringIt’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.
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.
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:
classBasicTypes:NSObject,HandyJSON{dynamicvarint:Int=0{
didSet {print("oldValue: ", oldValue)}
willSet {print("newValue: ", newValue)}}publicoverriderequiredinit(){}}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.
classBasicTypes:HandyJSON{varint:Int?requiredinit(){}func didFinishMapping(){print("you can fill some observing logic here")}}It may help.
It your enum conform to RawRepresentable protocol, please look into Support Enum Property. Or use the EnumTransform:
enumEnumType:String{case type1, type2
}classBasicTypes:HandyJSON{vartype:EnumType?func mapping(mapper:HelpingMapper){
mapper <<<
type <--EnumTransform()}requiredinit(){}}letobject=BasicTypes()
object.type =EnumType.type2
print(object.toJSONString()!)letmappedObject=BasicTypes.deserialize(from: object.toJSONString()!)!
print(mappedObject.type)Otherwise, you should implement your custom mapping function.
enumEnumType{case type1, type2
}classBasicTypes:HandyJSON{vartype:EnumType?func mapping(mapper:HelpingMapper){
mapper <<<
type <--TransformOf<EnumType,String>(fromJSON:{(rawString)->EnumType?iniflet _str = rawString {switch(_str){case"type1":returnEnumType.type1
case"type2":returnEnumType.type2
default:returnnil}}returnnil}, toJSON:{(enumType)->String?iniflet _type = enumType {switch(_type){caseEnumType.type1:return"type1"caseEnumType.type2:return"type2"}}returnnil})}requiredinit(){}}- 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.
HandyJSON is released under the Apache License, Version 2.0. See LICENSE for details.
