JSONHelper - ✌ Convert anything into anything in one operation; JSON data into class instances, hex strings into UIColor/NSColor, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!

Overview

JSONHelper CocoaPods CocoaPods

Build Status CocoaPods Gitter

Convert anything into anything in one operation; hex strings into UIColor/NSColor, JSON strings into class instances, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!

Latest version requires iOS 8+ and Xcode 7.3+

GitAds

Table of Contents

  1. Installation
  2. The <-- Operator
  3. Convertible Protocol
  4. Deserializable Protocol (with JSON deserialization example)
  5. Serializable Protocol

Installation

CocoaPods

Add the following line in your Podfile.

pod "JSONHelper"

Carthage

Add the following line to your Cartfile.

github "isair/JSONHelper"

Then do carthage update. After that, add the framework to your project.

The <-- Operator

The <-- operator takes the value on its right hand side and tries to convert it into the type of the value on its left hand side. If the conversion fails, an error is logged on debug builds. If it's successful, the value of the left hand side variable is overwritten. It's chainable as well.

If the right hand side value is nil or the conversion fails, and the left hand side variable is an optional, then nil is assigned to it. When the left hand side is non-optional, the current value of the left hand side variable is left untouched.

Using this specification let's assume you have a dictionary response that you retrieved from some API with hex color strings in it, under the key colors, that you want to convert into an array of UIColor instances. Also, to fully use everything we know, let's also assume that we want to have a default value for our color array in case the value for the key we're looking for does not exist (is nil).

var colors = [UIColor.blackColor(), UIColor.whiteColor()]
// Assume we have response { "colors": ["#aaa", "#b06200aa"] }
colors <-- response[colorsKey]

Convertible Protocol

If your type is a simple value-like type, adopting the Convertible protocol is the way to make your type work with the <-- operator.

Example:

struct Vector2D: Convertible {
  var x: Double = 0
  var y: Double = 0

  init(x: Double, y: Double) {
    self.x = x
    self.y = y
  }

  static func convertFromValue<T>(value: T?) throws -> Self? {
    guard let value = value else { return nil }

    if let doubleTupleValue = value as? (Double, Double) {
      return self.init(x: doubleTupleValue.0, y: doubleTupleValue.1)
    }

    throw ConversionError.UnsupportedType
  }
}
var myVector: Vector2D?
myVector <-- (1.0, 2.7)

Deserializable Protocol

While you can basically adopt the Convertible protocol for any type, if your type is always converted from a dictionary or a JSON string then things can get a lot easier with the Deserializable protocol.

Example:

class User: Deserializable {
  static let idKey = "id"
  static let emailKey = "email"
  static let nameKey = "name"
  static let avatarURLKey = "avatar_url"

  private(set) var id: String?
  private(set) var email: String?
  private(set) var name = "Guest"
  private(set) var avatarURL = NSURL(string: "https://mysite.com/assets/default-avatar.png")

  required init(dictionary: [String : AnyObject]) {
    id <-- dictionary[User.idKey]
    email <-- dictionary[User.emailKey]
    name <-- dictionary[User.nameKey]
    avatarURL <-- dictionary[User.avatarURLKey]
  }
}
var myUser: User?
user <-- apiResponse["user"]

Serializable Protocol

// Serialization is coming soon. I'll probably not add a new protocol and just rename and update the Deserializable protocol and turn it into a mixin.

Comments
  • Should properties get set to nil if the JSON object doesn't contain the key?

    Should properties get set to nil if the JSON object doesn't contain the key?

    Something I noticed in:

    public func <<<<T>(inout property: T?, value: AnyObject?) -> T?
    

    Is that it sets property = nil in the event that value is nil. Generally speaking, it'll be nil if the JSON object just doesn't contain that key at all. This can have the effect of changing whatever value was in your Swift object to nil if you receive a JSON payload that doesn't contain the key. I thought the common paradigm in JSON was to pass the key down but with a null object (NSNull in Foundation-land) if you wanted to explicitly delete a value from an object on the clients.

    Basically, my issue is this. Because my app receives JSON payloads from two sources, a web service API and a WebSocket, it has to be able to update existing object instances from a JSON payload. I've implemented it like:

    public class User : ModelObject {
        public var name: String?
        public var handle: String?
        public var createdAt: NSDate?
        public var updatedAt: NSDate?
    
        public required init(data: [String : AnyObject]) {
            super.init(data: data)
            updateWithJSON(data)
        }
    
        public override func updateWithJSON(data: [String : AnyObject]) {
            super.updateWithJSON(data)
            name <<< data["name"]
            handle <<< data["handle"]
            createdAt <<< data["created_at"]
            updatedAt <<< data["updated_at"]
        }
    }
    

    The response from the Web API is something like:

    {
        "id" : "38459979-e5f9-4c50-8bf6-8721bae33b4e",
        "name" : "First Last",
        "handle" : "first",
        "created_at" : 1370263044,
        "updated_at" : 1370263044 
    }
    

    I'm successfully parsing this into a User object. Then, I get a payload from WebSocket like this:

    {
        "id" : "38459979-e5f9-4c50-8bf6-8721bae33b4e",
        "name": "Something Else"
    }
    

    This now deletes the values that were stored in handle, createdAt and updatedAt! I'm opening this as an issue instead of a pull request because I don't know what the consensus is on this kind of thing. Do people expect this deletion behaviour? If so, I'm happy to write a new operator that doesn't do the deletion, something like <<<= maybe?

    ┆Issue is synchronized with this Asana task

    discussion 
    opened by tyrone-sudeium 6
  • Reimplementation JSONHelper with the magic of Generics

    Reimplementation JSONHelper with the magic of Generics

    Hey.

    I noticed that there are so many repeating code in JSONHelper, so I just reimplement most of it. I try to use generics as much as I can to simplify the code, and now I make a little success. With less then half the origin code, it can do the same things as before, even more features were added. https://github.com/lancy/JSONHelper It's compatible to most of the origin APIs, not all of them, but If you like it, I will make a pull request.

    By the way, hope you don't mind that I'm planning to create another individual JSON Library to add more features (something like serialization), and It may refer some of your code. I will make a statements to thanks you and this project.

    Have fun!

    ┆Issue is synchronized with this Asana task

    enhancement 
    opened by lancy 5
  • CocoaPods: Xcode build error

    CocoaPods: Xcode build error

    Trying to build project with JSONHelper pod and got this error:

    podfile:

    source 'https://github.com/CocoaPods/Specs.git'
    platform:ios, '7.0'
    link_with ['ClubApp','ClubAppTests']
    
    pod 'Facebook-iOS-SDK', '~> 3.20'
    pod 'AFNetworking', '~> 2.4'
    pod 'IOSLinkedInAPI', '~> 2.0'
    pod 'JSONHelper', :git => 'https://github.com/isair/JSONHelper.git', :tag => '1.4.0'
    

    console output:

    Libtool /Users/ndelitski/Library/Developer/Xcode/DerivedData/ClubApp-bjvgmiummzkehjfcjiuntqrfglcl/Build/Products/Debug-iphonesimulator/libPods-JSONHelper.a normal x86_64
        cd /Users/ndelitski/Repo/club/ClubApp.iOS/Pods
        export IPHONEOS_DEPLOYMENT_TARGET=7.0
        export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
        /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static -arch_only x86_64 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -L/Users/ndelitski/Library/Developer/Xcode/DerivedData/ClubApp-bjvgmiummzkehjfcjiuntqrfglcl/Build/Products/Debug-iphonesimulator -filelist /Users/ndelitski/Library/Developer/Xcode/DerivedData/ClubApp-bjvgmiummzkehjfcjiuntqrfglcl/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-JSONHelper.build/Objects-normal/x86_64/Pods-JSONHelper.LinkFileList -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator -Xlinker -force_load -Xlinker /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_iphonesimulator.a -Xlinker -add_ast_path -Xlinker /Users/ndelitski/Library/Developer/Xcode/DerivedData/ClubApp-bjvgmiummzkehjfcjiuntqrfglcl/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-JSONHelper.build/Objects-normal/x86_64/Pods_JSONHelper.swiftmodule -framework Foundation -o /Users/ndelitski/Library/Developer/Xcode/DerivedData/ClubApp-bjvgmiummzkehjfcjiuntqrfglcl/Build/Products/Debug-iphonesimulator/libPods-JSONHelper.a
    
    error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: unknown option character `X' in: -Xlinker
    Usage: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static [-] file [...] [-filelist listfile[,dirname]] [-arch_only arch] [-sacLT] [-no_warning_for_no_symbols]
    Usage: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -dynamic [-] file [...] [-filelist listfile[,dirname]] [-arch_only arch] [-o output] [-install_name name] [-compatibility_version #] [-current_version #] [-seg1addr 0x#] [-segs_read_only_addr 0x#] [-segs_read_write_addr 0x#] [-seg_addr_table <filename>] [-seg_addr_table_filename <file_system_path>] [-all_load] [-noall_load]
    

    Attaching file directly to project works fine, but i want to do this using CocoaPods, could you help please?

    question 
    opened by ndelitski 5
  • tvOS Support

    tvOS Support

    Hello JSONHelper team,

    I saw that on your podspec, you added the tvOS support on the master, 4 days ago. However, there is no new version uploaded since then.

    Do you think it could be possible to publish a 1.7.0 of JSONHelper library on Cocoapods in order to ship this feature ?

    Best regards,

    Lorenzo.

    ┆Issue is synchronized with this Asana task

    enhancement 
    opened by ldi13 4
  • "application: JSONHelper" sometimes inserted for null values in JSON

    We've got several computers using JSONHelper to parse JSON for Applescripts.

    I've got some behavior that seems very strange to me.

    Running the same version of the Applescript, and the same version of JSONHelper, on the same JSON data, on some computers it is returning the null values to Applescript as the name of the application. That is, the null values get returned as: application "JSONHelper" in the returned JSON data. This doesn't happen on other computers.

    The files can be downloaded here: https://www.dropbox.com/s/sgepla2fpspdnzq/JSONHelper_Issue.zip?dl=0

    It's got the original JSON data, and the different responses returned by running that through JSONHelper on different computers. At least three computers are returning the version with "application: JSONHelper" substituted for all null values.

    I'd appreciate any help/insight. Whatever's going on, I don't understand how I'm getting different results when I use the same JSON data with the same Applescript and the same version of JSONHelper.

    Thanks in advance for any help.

    bug 
    opened by ingling 4
  • Warnings

    Warnings

    I got the following warnings:

    Conversion.swift:137:42: cast from 'NSDictionary?' to unrelated type '[T : AnyObject]' always fails
    if let elements = rhs as? NSDictionary as? [T : AnyObject] {
                        ~~~~~~~~~~~~~~~~~~~~ ^   ~~~~~~~~~~~~~~~
    
    
    Deserialization.swift:122:42: cast from 'NSDictionary?' to unrelated type '[T : AnyObject]' always fails
    if let elements = rhs as? NSDictionary as? [T : AnyObject] {
                        ~~~~~~~~~~~~~~~~~~~~ ^   ~~~~~~~~~~~~~~~
    
    

    ┆Issue is synchronized with this Asana task

    opened by george-gw 3
  • Not able to use `let`

    Not able to use `let`

    The readme says: "// You can also use let instead of var if you want."

    I don't find this to be the case. Changing a var x to a let x gives the error "Variable self.x passed by reference before being initialized".

    How can I use let x?

    opened by rafalio 3
  • How to handle in polymorphism

    How to handle in polymorphism

    Suppose I have a base class named Accessory, and there are some subclass inherit from it, like AudioAccessory, LabelAccessory, ContentAccessory, and a type to identify them.

    class Accessory {
        var type: Int
    }
    
    class LabelAccessory: Accessory {
        var label: String
    }
    
    class ContentAccessory: Accessory {
        var content: String
    }
    

    How do I convert a JSON into [Accessory] ? Should I write my custom deserialisation function, switch type to init object in different class? something like:

    public func <-- (inout instance: [Accessory]?, dataObject: AnyObject?) --> [Accessory]? {
      if let dataArray = dataObject as? [JSONDictionary] {
        array = [Accessory]()
        for data in dataArray {
            let baseObject = Accessory(data: data)
            switch baseObject.type {
                case Label:
                    array!.append(LabelAccessory(data: data))
                    .....
           }
        }
      } else {
        array = nil
      }
      return array
    }
    

    Is there a better way to do that? Thank you so much

    question 
    opened by lancy 3
  • Swift 1.2 Support

    Swift 1.2 Support

    Hey there! XCode 6.3 was recently forced upon my machine and with it came Swift 1.2. JSONHelper doesn't comply with this new version of Swift, and I was wondering if there were any plans to update the library to be compliant. There don't seem to be a lot of changes required, but I don't want to duplicate work someone is already doing. I think I could make a PR, but my knowledge of Swift isn't great.

    screen shot 2015-04-14 at 4 05 29 pm

    opened by ox 3
  • Bugfix: for Release builds

    Bugfix: for Release builds

    We discovered a bug when using JSONHelper in release builds. We have modified the tests to run in release builds to display the error and figured out a workaround until a more robust solution can be found.

    opened by StyleOffDev 3
  • Not works with latest version of Xcode and Swift 2.2

    Not works with latest version of Xcode and Swift 2.2

    I'm getting this error:

    Module file was created by an older version of the compiler; rebuild 'JSONHelper' and try again:

    ┆Issue is synchronized with this Asana task

    opened by albetoetecnia 2
  • Request: Changing Deserializable to require init? as oppose to init

    Request: Changing Deserializable to require init? as oppose to init

    When deserializing, I might pass a completely irrelevant object to init of a deserializable object and they have to handle it. having the option to return nil and say there are not enough information to initialize this object would be great specially since <-- operator does return an optional anyway.

    ┆Issue is synchronized with this Asana task

    enhancement 
    opened by peymanmortazavi 1
  • Request: Object serialization to JSON string

    Request: Object serialization to JSON string

    It would be awesome to implement serialization of swift objects to JSON strings :+1:
    Is it possible to do so using this excellent library ? Thank you...

    ┆Issue is synchronized with this Asana task

    enhancement 
    opened by OmarKan 3
Releases(2.2.0)
Owner
Baris Sencan
I repeatedly exert minimal force on small pieces of plastic
Baris Sencan
A fast, convenient and nonintrusive conversion framework between JSON and model. Your model class doesn't need to extend any base class. You don't need to modify any model file.

MJExtension A fast, convenient and nonintrusive conversion framework between JSON and model. 转换速度快、使用简单方便的字典转模型框架 ?? ✍??Release Notes: more details Co

M了个J 8.5k Jan 3, 2023
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

JSONModel - Magical Data Modeling Framework for JSON JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS

JSONModel 6.9k Dec 8, 2022
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

JSONModel - Magical Data Modeling Framework for JSON JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS

JSONModel 6.8k Nov 19, 2021
ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects to and from JSON.

ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Tristan Himmelman 9k Jan 2, 2023
CLT to convert JSON5 to JSON

JSON5toJSON A small command line tool to convert JSON5 to JSON. Runs on macOS 12 (Monterey). Installation Install using Mint. $ mint install auramagi/

Mike Apurin 1 Nov 4, 2021
JSONJoy - Convert JSON to Swift objects

JSONJoy Convert JSON to Swift objects. The Objective-C counterpart can be found here: JSONJoy. Parsing JSON in Swift has be likened to a trip through

Dalton 350 Oct 15, 2022
AlamofireObjectMappe - An Alamofire extension which converts JSON response data into swift objects using ObjectMapper

AlamofireObjectMapper An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper. Usage Given a U

Tristan Himmelman 2.6k Dec 29, 2022
An extension for Alamofire that converts JSON data into Decodable objects.

Swift 4 introduces a new Codable protocol that lets you serialize and deserialize custom data types without writing any special code and without havin

Nikita Ermolenko 749 Dec 5, 2022
Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON.

JSONFeed Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON. For more information about this new feed format visit: https:/

Toto Tvalavadze 31 Nov 22, 2021
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

John Lui 454 Oct 30, 2022
JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift.

JSEN /ˈdʒeɪsən/ JAY-sən JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift. A JSON, as defined in the EC

Roger Oba 8 Nov 22, 2022
JSON-Practice - JSON Practice With Swift

JSON Practice Vista creada con: Programmatic + AutoLayout Breve explicación de l

Vanesa Giselle Korbenfeld 0 Oct 29, 2021
Ss-json - High-performance json parsing in swift

json 0.1.1 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
Swift-json - High-performance json parsing in swift

json 0.1.4 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable

Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable. Elevate should no longer be used for

Nike Inc. 611 Oct 23, 2022
HandyJSON is a framework written in Swift which to make converting model objects to and from JSON easy on iOS.

HandyJSON To deal with crash on iOS 14 beta4 please try version 5.0.3-beta HandyJSON is a framework written in Swift which to make converting model ob

Alibaba 4.1k Dec 29, 2022
Library of Swiftui Views conforming to Codable, meaning we can produce JSON driven UI!

CodableView Library of Swiftui Views conforming to Codable, meaning we can produce JSON driven UI! Adding a CodableView Type Create View that conforms

Daniel Bolella 3 Apr 2, 2022
JOP is the Json organization program. It can run on any platform that supports Swift.

JOP JOP is a program organized in JSON files. It is based on Swift, provides a syntax similar to Swift, and has the same strong security as Swift. Thi

Underthestars-zhy 1 Nov 18, 2021
From JSON to Core Data and back.

Groot Groot provides a simple way of serializing Core Data object graphs from or into JSON. It uses annotations in the Core Data model to perform the

Guille Gonzalez 533 Nov 3, 2022