{"id":1727,"url":"https://github.com/alibaba/handyjson","last_synced_at":"2025-05-14T02:08:57.995Z","repository":{"id":41086458,"uuid":"68666038","full_name":"alibaba/HandyJSON","owner":"alibaba","description":"A handy swift json-object serialization/deserialization library","archived":false,"fork":false,"pushed_at":"2024-03-08T11:30:52.000Z","size":541,"stargazers_count":4260,"open_issues_count":233,"forks_count":669,"subscribers_count":77,"default_branch":"master","last_synced_at":"2025-05-11T00:31:57.141Z","etag":null,"topics":["deserialization","json","json-fields","mapping","serialization","swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alibaba.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-09-20T02:31:15.000Z","updated_at":"2025-04-28T18:05:20.000Z","dependencies_parsed_at":"2024-06-18T10:54:27.455Z","dependency_job_id":null,"html_url":"https://github.com/alibaba/HandyJSON","commit_stats":{"total_commits":263,"total_committers":25,"mean_commits":10.52,"dds":0.5171102661596958,"last_synced_commit":"f0b15db3bc0c51e935ea2385d6e33d412f04fffe"},"previous_names":[],"tags_count":36,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alibaba%2FHandyJSON","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alibaba%2FHandyJSON/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alibaba%2FHandyJSON/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alibaba%2FHandyJSON/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alibaba","download_url":"https://codeload.github.com/alibaba/HandyJSON/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254053223,"owners_count":22006717,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deserialization","json","json-fields","mapping","serialization","swift"],"created_at":"2024-01-05T20:15:54.371Z","updated_at":"2025-05-14T02:08:52.983Z","avatar_url":"https://github.com/alibaba.png","language":"Swift","readme":"# HandyJSON\n\n***To deal with crash on iOS 15 beta3 please try version 5.0.4-beta***\n\nHandyJSON is a framework written in Swift which to make converting model objects( **pure classes/structs** ) to and from JSON easy on iOS.\n\nCompared 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**).\n\nHandyJSON 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.\n\n[![Build Status](https://travis-ci.org/alibaba/HandyJSON.svg?branch=master)](https://travis-ci.org/alibaba/HandyJSON)\n[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)\n[![Cocoapods Version](https://img.shields.io/cocoapods/v/HandyJSON.svg?style=flat)](http://cocoadocs.org/docsets/HandyJSON)\n[![Cocoapods Platform](https://img.shields.io/cocoapods/p/HandyJSON.svg?style=flat)](http://cocoadocs.org/docsets/HandyJSON)\n[![Codecov branch](https://img.shields.io/codecov/c/github/alibaba/HandyJSON/master.svg?style=flat)](https://codecov.io/gh/alibaba/HandyJSON/branch/master)\n\n## [中文文档](./README_cn.md)\n\n## 交流群\n\n群号: 581331250\n\n![交流群](qq_group.png)\n\n## Sample Code\n\n### Deserialization\n\n```swift\nclass BasicTypes: HandyJSON {\n    var int: Int = 2\n    var doubleOptional: Double?\n    var stringImplicitlyUnwrapped: String!\n\n    required init() {}\n}\n\nlet jsonString = \"{\\\"doubleOptional\\\":1.1,\\\"stringImplicitlyUnwrapped\\\":\\\"hello\\\",\\\"int\\\":1}\"\nif let object = BasicTypes.deserialize(from: jsonString) {\n    print(object.int)\n    print(object.doubleOptional!)\n    print(object.stringImplicitlyUnwrapped)\n}\n```\n\n### Serialization\n\n```swift\n\nlet object = BasicTypes()\nobject.int = 1\nobject.doubleOptional = 1.1\nobject.stringImplicitlyUnwrapped = “hello\"\n\nprint(object.toJSON()!) // serialize to dictionary\nprint(object.toJSONString()!) // serialize to JSON string\nprint(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string\n```\n\n# Content\n\n- [Features](#features)\n- [Requirements](#requirements)\n- [Installation](#installation)\n    - [Cocoapods](#cocoapods)\n    - [Carthage](#carthage)\n    - [Manually](#manually)\n- [Deserialization](#deserialization)\n    - [The Basics](#the-basics)\n    - [Support Struct](#support-struct)\n    - [Support Enum Property](#support-enum-property)\n    - [Optional/ImplicitlyUnwrappedOptional/Collections/...](#optionalimplicitlyunwrappedoptionalcollections)\n    - [Designated Path](#designated-path)\n    - [Composition Object](#composition-object)\n    - [Inheritance Object](#inheritance-object)\n    - [JSON Array](#json-array)\n    - [Mapping From Dictionary](#mapping-from-dictionary)\n    - [Custom Mapping](#custom-mapping)\n    - [Date/Data/URL/Decimal/Color](#datedataurldecimalcolor)\n    - [Exclude Property](#exclude-property)\n    - [Update Existing Model](#update-existing-model)\n    - [Supported Property Type](#supported-property-type)\n- [Serialization](#serialization)\n    - [The Basics](#the-basics)\n    - [Mapping And Excluding](#mapping-and-excluding)\n- [FAQ](#faq)\n- [To Do](#to-do)\n\n# Features\n\n* Serialize/Deserialize Object/JSON to/From JSON/Object\n\n* Naturally use object property name for mapping, no need to specify a mapping relationship\n\n* Support almost all types in Swift, including enum\n\n* Support struct\n\n* Custom transformations\n\n* Type-Adaption, such as string json field maps to int property, int json field maps to string property\n\nAn overview of types supported can be found at file: [BasicTypes.swift](./HandyJSONTest/BasicTypes.swift)\n\n# Requirements\n\n* iOS 8.0+/OSX 10.9+/watchOS 2.0+/tvOS 9.0+\n\n* Swift 3.0+ / Swift 4.0+ / Swift 5.0+\n\n# Installation\n\n**To use with Swift 5.0/5.1 ( Xcode 10.2+/11.0+ ), version == 5.0.2**\n\n**To use with Swift 4.2 ( Xcode 10 ), version == 4.2.0**\n\n**To use with Swift 4.0, version \u003e= 4.1.1**\n\n**To use with Swift 3.x, version \u003e= 1.8.0**\n\nFor Legacy Swift2.x support, take a look at the [swift2 branch](https://github.com/alibaba/HandyJSON/tree/master_for_swift_2x).\n\n## Cocoapods\n\nAdd the following line to your `Podfile`:\n\n```\npod 'HandyJSON', '~\u003e 5.0.2'\n```\n\nThen, run the following command:\n\n```\n$ pod install\n```\n\n## Carthage\n\nYou can add a dependency on `HandyJSON` by adding the following line to your `Cartfile`:\n\n```\ngithub \"alibaba/HandyJSON\" ~\u003e 5.0.2\n```\n\n## Manually\n\nYou can integrate `HandyJSON` into your project manually by doing the following steps:\n\n* Open up `Terminal`, `cd` into your top-level project directory, and add `HandyJSON` as a submodule:\n\n```\ngit init \u0026\u0026 git submodule add https://github.com/alibaba/HandyJSON.git\n```\n\n* Open the new `HandyJSON` folder, drag the `HandyJSON.xcodeproj` into the `Project Navigator` of your project.\n\n* Select your application project in the `Project Navigator`, open the `General` panel in the right window.\n\n* Click on the `+` button under the `Embedded Binaries` section.\n\n* You will see two different `HandyJSON.xcodeproj` folders each with four different versions of the HandyJSON.framework nested inside a Products folder.\n\u003e It does not matter which Products folder you choose from, but it does matter which HandyJSON.framework you choose.\n\n* Select one of the four `HandyJSON.framework` which matches the platform your Application should run on.\n\n* Congratulations!\n\n# Deserialization\n\n## The Basics\n\nTo support deserialization from JSON, a class/struct need to conform to 'HandyJSON' protocol. It's truly protocol, not some class inherited from NSObject.\n\nTo conform to 'HandyJSON', a class need to implement an empty initializer.\n\n```swift\nclass BasicTypes: HandyJSON {\n    var int: Int = 2\n    var doubleOptional: Double?\n    var stringImplicitlyUnwrapped: String!\n\n    required init() {}\n}\n\nlet jsonString = \"{\\\"doubleOptional\\\":1.1,\\\"stringImplicitlyUnwrapped\\\":\\\"hello\\\",\\\"int\\\":1}\"\nif let object = BasicTypes.deserialize(from: jsonString) {\n    // …\n}\n```\n\n## Support Struct\n\nFor struct, since the compiler provide a default empty initializer, we use it for free.\n\n```swift\nstruct BasicTypes: HandyJSON {\n    var int: Int = 2\n    var doubleOptional: Double?\n    var stringImplicitlyUnwrapped: String!\n}\n\nlet jsonString = \"{\\\"doubleOptional\\\":1.1,\\\"stringImplicitlyUnwrapped\\\":\\\"hello\\\",\\\"int\\\":1}\"\nif let object = BasicTypes.deserialize(from: jsonString) {\n    // …\n}\n```\n\nBut 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).\n\n## Support Enum Property\n\nTo be convertable, An `enum` must conform to `HandyJSONEnum` protocol. Nothing special need to do now.\n\n```swift\nenum AnimalType: String, HandyJSONEnum {\n    case Cat = \"cat\"\n    case Dog = \"dog\"\n    case Bird = \"bird\"\n}\n\nstruct Animal: HandyJSON {\n    var name: String?\n    var type: AnimalType?\n}\n\nlet jsonString = \"{\\\"type\\\":\\\"cat\\\",\\\"name\\\":\\\"Tom\\\"}\"\nif let animal = Animal.deserialize(from: jsonString) {\n    print(animal.type?.rawValue)\n}\n```\n\n## Optional/ImplicitlyUnwrappedOptional/Collections/...\n\n'HandyJSON' support classes/structs composed of `optional`, `implicitlyUnwrappedOptional`, `array`, `dictionary`, `objective-c base type`, `nested type` etc. properties.\n\n```swift\nclass BasicTypes: HandyJSON {\n    var bool: Bool = true\n    var intOptional: Int?\n    var doubleImplicitlyUnwrapped: Double!\n    var anyObjectOptional: Any?\n\n    var arrayInt: Array\u003cInt\u003e = []\n    var arrayStringOptional: Array\u003cString\u003e?\n    var setInt: Set\u003cInt\u003e?\n    var dictAnyObject: Dictionary\u003cString, Any\u003e = [:]\n\n    var nsNumber = 2\n    var nsString: NSString?\n\n    required init() {}\n}\n\nlet object = BasicTypes()\nobject.intOptional = 1\nobject.doubleImplicitlyUnwrapped = 1.1\nobject.anyObjectOptional = \"StringValue\"\nobject.arrayInt = [1, 2]\nobject.arrayStringOptional = [\"a\", \"b\"]\nobject.setInt = [1, 2]\nobject.dictAnyObject = [\"key1\": 1, \"key2\": \"stringValue\"]\nobject.nsNumber = 2\nobject.nsString = \"nsStringValue\"\n\nlet jsonString = object.toJSONString()!\n\nif let object = BasicTypes.deserialize(from: jsonString) {\n    // ...\n}\n```\n\n## Designated Path\n\n`HandyJSON` supports deserialization from designated path of JSON.\n\n```swift\nclass Cat: HandyJSON {\n    var id: Int64!\n    var name: String!\n\n    required init() {}\n}\n\nlet jsonString = \"{\\\"code\\\":200,\\\"msg\\\":\\\"success\\\",\\\"data\\\":{\\\"cat\\\":{\\\"id\\\":12345,\\\"name\\\":\\\"Kitty\\\"}}}\"\n\nif let cat = Cat.deserialize(from: jsonString, designatedPath: \"data.cat\") {\n    print(cat.name)\n}\n```\n\n## Composition Object\n\nNotice that all the properties of a class/struct need to deserialized should be type conformed to `HandyJSON`.\n\n```swift\nclass Component: HandyJSON {\n    var aInt: Int?\n    var aString: String?\n\n    required init() {}\n}\n\nclass Composition: HandyJSON {\n    var aInt: Int?\n    var comp1: Component?\n    var comp2: Component?\n\n    required init() {}\n}\n\nlet jsonString = \"{\\\"num\\\":12345,\\\"comp1\\\":{\\\"aInt\\\":1,\\\"aString\\\":\\\"aaaaa\\\"},\\\"comp2\\\":{\\\"aInt\\\":2,\\\"aString\\\":\\\"bbbbb\\\"}}\"\n\nif let composition = Composition.deserialize(from: jsonString) {\n    print(composition)\n}\n```\n\n## Inheritance Object\n\nA subclass need deserialization, it's superclass need to conform to `HandyJSON`.\n\n```swift\nclass Animal: HandyJSON {\n    var id: Int?\n    var color: String?\n\n    required init() {}\n}\n\nclass Cat: Animal {\n    var name: String?\n\n    required init() {}\n}\n\nlet jsonString = \"{\\\"id\\\":12345,\\\"color\\\":\\\"black\\\",\\\"name\\\":\\\"cat\\\"}\"\n\nif let cat = Cat.deserialize(from: jsonString) {\n    print(cat)\n}\n```\n\n## JSON Array\n\nIf the first level of a JSON text is an array, we turn it to objects array.\n\n```swift\nclass Cat: HandyJSON {\n    var name: String?\n    var id: String?\n\n    required init() {}\n}\n\nlet jsonArrayString: String? = \"[{\\\"name\\\":\\\"Bob\\\",\\\"id\\\":\\\"1\\\"}, {\\\"name\\\":\\\"Lily\\\",\\\"id\\\":\\\"2\\\"}, {\\\"name\\\":\\\"Lucy\\\",\\\"id\\\":\\\"3\\\"}]\"\nif let cats = [Cat].deserialize(from: jsonArrayString) {\n    cats.forEach({ (cat) in\n        // ...\n    })\n}\n```\n\n## Mapping From Dictionary\n\n`HandyJSON` support mapping swift dictionary to model.\n\n```swift\nvar dict = [String: Any]()\ndict[\"doubleOptional\"] = 1.1\ndict[\"stringImplicitlyUnwrapped\"] = \"hello\"\ndict[\"int\"] = 1\nif let object = BasicTypes.deserialize(from: dict) {\n    // ...\n}\n```\n\n## Custom Mapping\n\n`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.\n\nWe bring the transformer from [`ObjectMapper`](https://github.com/Hearst-DD/ObjectMapper). If you are familiar with it, it’s almost the same here.\n\n```swift\nclass Cat: HandyJSON {\n    var id: Int64!\n    var name: String!\n    var parent: (String, String)?\n    var friendName: String?\n\n    required init() {}\n\n    func mapping(mapper: HelpingMapper) {\n        // specify 'cat_id' field in json map to 'id' property in object\n        mapper \u003c\u003c\u003c\n            self.id \u003c-- \"cat_id\"\n\n        // specify 'parent' field in json parse as following to 'parent' property in object\n        mapper \u003c\u003c\u003c\n            self.parent \u003c-- TransformOf\u003c(String, String), String\u003e(fromJSON: { (rawString) -\u003e (String, String)? in\n                if let parentNames = rawString?.characters.split(separator: \"/\").map(String.init) {\n                    return (parentNames[0], parentNames[1])\n                }\n                return nil\n            }, toJSON: { (tuple) -\u003e String? in\n                if let _tuple = tuple {\n                    return \"\\(_tuple.0)/\\(_tuple.1)\"\n                }\n                return nil\n            })\n\n        // specify 'friend.name' path field in json map to 'friendName' property\n        mapper \u003c\u003c\u003c\n            self.friendName \u003c-- \"friend.name\"\n    }\n}\n\nlet jsonString = \"{\\\"cat_id\\\":12345,\\\"name\\\":\\\"Kitty\\\",\\\"parent\\\":\\\"Tom/Lily\\\",\\\"friend\\\":{\\\"id\\\":54321,\\\"name\\\":\\\"Lily\\\"}}\"\n\nif let cat = Cat.deserialize(from: jsonString) {\n    print(cat.id)\n    print(cat.parent)\n    print(cat.friendName)\n}\n```\n\n## Date/Data/URL/Decimal/Color\n\n`HandyJSON` prepare some useful transformer for some none-basic type.\n\n```swift\nclass ExtendType: HandyJSON {\n    var date: Date?\n    var decimal: NSDecimalNumber?\n    var url: URL?\n    var data: Data?\n    var color: UIColor?\n\n    func mapping(mapper: HelpingMapper) {\n        mapper \u003c\u003c\u003c\n            date \u003c-- CustomDateFormatTransform(formatString: \"yyyy-MM-dd\")\n\n        mapper \u003c\u003c\u003c\n            decimal \u003c-- NSDecimalNumberTransform()\n\n        mapper \u003c\u003c\u003c\n            url \u003c-- URLTransform(shouldEncodeURLString: false)\n\n        mapper \u003c\u003c\u003c\n            data \u003c-- DataTransform()\n\n        mapper \u003c\u003c\u003c\n            color \u003c-- HexColorTransform()\n    }\n\n    public required init() {}\n}\n\nlet object = ExtendType()\nobject.date = Date()\nobject.decimal = NSDecimalNumber(string: \"1.23423414371298437124391243\")\nobject.url = URL(string: \"https://www.aliyun.com\")\nobject.data = Data(base64Encoded: \"aGVsbG8sIHdvcmxkIQ==\")\nobject.color = UIColor.blue\n\nprint(object.toJSONString()!)\n// it prints:\n// {\"date\":\"2017-09-11\",\"decimal\":\"1.23423414371298437124391243\",\"url\":\"https:\\/\\/www.aliyun.com\",\"data\":\"aGVsbG8sIHdvcmxkIQ==\",\"color\":\"0000FF\"}\n\nlet mappedObject = ExtendType.deserialize(from: object.toJSONString()!)!\nprint(mappedObject.date)\n...\n```\n\n## Exclude Property\n\nIf 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.\n\n```swift\nclass NotHandyJSONType {\n    var dummy: String?\n}\n\nclass Cat: HandyJSON {\n    var id: Int64!\n    var name: String!\n    var notHandyJSONTypeProperty: NotHandyJSONType?\n    var basicTypeButNotWantedProperty: String?\n\n    required init() {}\n\n    func mapping(mapper: HelpingMapper) {\n        mapper \u003e\u003e\u003e self.notHandyJSONTypeProperty\n        mapper \u003e\u003e\u003e self.basicTypeButNotWantedProperty\n    }\n}\n\nlet jsonString = \"{\\\"name\\\":\\\"cat\\\",\\\"id\\\":\\\"12345\\\"}\"\n\nif let cat = Cat.deserialize(from: jsonString) {\n    print(cat)\n}\n```\n\n## Update Existing Model\n\n`HandyJSON` support updating an existing model with given json string or dictionary.\n\n```swift\nclass BasicTypes: HandyJSON {\n    var int: Int = 2\n    var doubleOptional: Double?\n    var stringImplicitlyUnwrapped: String!\n\n    required init() {}\n}\n\nvar object = BasicTypes()\nobject.int = 1\nobject.doubleOptional = 1.1\n\nlet jsonString = \"{\\\"doubleOptional\\\":2.2}\"\nJSONDeserializer.update(object: \u0026object, from: jsonString)\nprint(object.int)\nprint(object.doubleOptional)\n```\n\n## Supported Property Type\n\n* `Int`/`Bool`/`Double`/`Float`/`String`/`NSNumber`/`NSString`\n\n* `RawRepresentable` enum\n\n* `NSArray/NSDictionary`\n\n* `Int8/Int16/Int32/Int64`/`UInt8/UInt16/UInt23/UInt64`\n\n* `Optional\u003cT\u003e/ImplicitUnwrappedOptional\u003cT\u003e` // T is one of the above types\n\n* `Array\u003cT\u003e` // T is one of the above types\n\n* `Dictionary\u003cString, T\u003e` // T is one of the above types\n\n* Nested of aboves\n\n# Serialization\n\n## The Basics\n\nNow, a class/model which need to serialize to JSON should also conform to `HandyJSON` protocol.\n\n```swift\nclass BasicTypes: HandyJSON {\n    var int: Int = 2\n    var doubleOptional: Double?\n    var stringImplicitlyUnwrapped: String!\n\n    required init() {}\n}\n\nlet object = BasicTypes()\nobject.int = 1\nobject.doubleOptional = 1.1\nobject.stringImplicitlyUnwrapped = “hello\"\n\nprint(object.toJSON()!) // serialize to dictionary\nprint(object.toJSONString()!) // serialize to JSON string\nprint(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string\n```\n\n## Mapping And Excluding\n\nIt’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.\n\n# FAQ\n\n## Q: Why the mapping function is not working in the inheritance object?\n\nA: 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.\n\nIt's the same with `didFinishMapping` function.\n\n## Q: Why my didSet/willSet is not working?\n\nA: 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.\n\nBut 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:\n\n```swift\nclass BasicTypes: NSObject, HandyJSON {\n    dynamic var int: Int = 0 {\n        didSet {\n            print(\"oldValue: \", oldValue)\n        }\n        willSet {\n            print(\"newValue: \", newValue)\n        }\n    }\n\n    public override required init() {}\n}\n```\n\nIn this situation, `NSObject` and `dynamic` are both needed.\n\nAnd in versions since `1.8.0`, `HandyJSON` offer a `didFinishMapping` function to allow you to fill some observing logic.\n\n```swift\nclass BasicTypes: HandyJSON {\n    var int: Int?\n\n    required init() {}\n\n    func didFinishMapping() {\n        print(\"you can fill some observing logic here\")\n    }\n}\n\n```\n\nIt may help.\n\n## Q: How to support Enum property?\n\nIt your enum conform to `RawRepresentable` protocol, please look into [Support Enum Property](#support-enum-property). Or use the `EnumTransform`:\n\n```swift\nenum EnumType: String {\n    case type1, type2\n}\n\nclass BasicTypes: HandyJSON {\n    var type: EnumType?\n\n    func mapping(mapper: HelpingMapper) {\n        mapper \u003c\u003c\u003c\n            type \u003c-- EnumTransform()\n    }\n\n    required init() {}\n}\n\nlet object = BasicTypes()\nobject.type = EnumType.type2\nprint(object.toJSONString()!)\nlet mappedObject = BasicTypes.deserialize(from: object.toJSONString()!)!\nprint(mappedObject.type)\n```\n\nOtherwise, you should implement your custom mapping function.\n\n```swift\nenum EnumType {\n    case type1, type2\n}\n\nclass BasicTypes: HandyJSON {\n    var type: EnumType?\n\n    func mapping(mapper: HelpingMapper) {\n        mapper \u003c\u003c\u003c\n            type \u003c-- TransformOf\u003cEnumType, String\u003e(fromJSON: { (rawString) -\u003e EnumType? in\n                if let _str = rawString {\n                    switch (_str) {\n                    case \"type1\":\n                        return EnumType.type1\n                    case \"type2\":\n                        return EnumType.type2\n                    default:\n                        return nil\n                    }\n                }\n                return nil\n            }, toJSON: { (enumType) -\u003e String? in\n                if let _type = enumType {\n                    switch (_type) {\n                    case EnumType.type1:\n                        return \"type1\"\n                    case EnumType.type2:\n                        return \"type2\"\n                    }\n                }\n                return nil\n            })\n    }\n\n    required init() {}\n}\n```\n\n# Credit\n\n* [reflection](https://github.com/Zewo/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.\n* [ObjectMapper](https://github.com/tristanhimmelman/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.\n\n# License\n\nHandyJSON is released under the Apache License, Version 2.0. See LICENSE for details.\n","funding_links":[],"categories":["Parsing","Libs","Data Management [🔝](#readme)"],"sub_categories":["JSON","Data Management","Other free courses"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falibaba%2Fhandyjson","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falibaba%2Fhandyjson","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falibaba%2Fhandyjson/lists"}