Framework for easily parsing your JSON data directly to Swift object.

Overview

Json_Parser_Image

CI Status Version License Platform Language codecov.io

Server sends the all JSON data in black and white format i.e. its all strings & we make hard efforts to typecast them into their respective datatypes as per our model class.

Now, there's comes JSONParserSwift framework between the server data and our code to magically converts those strings into the required respective datatypes as per our model classes without writing any code.

Requirements

Installation

JSONParserSwift is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "JSONParserSwift"

Swift 3 support

For using the framework on Swift 3 use the branch swift-3.2 or install version 1.1.3 using CocoaPods, use following line in your Podfile:

pod 'JSONParserSwift', '1.1.3'

Implementation

To parse any JSON String or Dictionary to your model you have to create a class and subclass it by ParsableModel. Now you will need to create the properties in the model class. You can create these properties with same name or different name as keys in json string. If you declare properties with same name as key in json then you need to declare only properties. But if you want to have different names for properties and keys then you need to conform protocol JSONKeyCoder and implement method func key(for key: String) -> String?

Example

If you have to parse following JSON String:

{
  "responseStatus": {
    "statusCode": 101,
    "message": "Error Message"
  },
  "responseData": {
    "employeeId": 1002,
    "employeeName": "Demo Employee",
    "employeeEmail": "[email protected]",
    "employeeDepartment": "IT"
  }
}

You will need to create models as follows:

class BaseResponse: ParsableModel {
  var responseStatus: ResponseStatus?
  var responseData: Employee?
}

class ResponseStatus: ParsableModel {
  var statusCode: NSNumber?
  var message: String?
}

class Employee: ParsableModel {
  var employeeId: NSNumber?
  var employeeName: String?
  var employeeEmail: String?
  var employeeDepartment: String?
}

Now to parse the JSON you just need to call following method:

do {
  let baseResponse: BaseResponse = try JSONParserSwift.parse(string: jsonString)
  // Use base response object here
} catch {
  print(error)
}

The model can have reference to other model's which are subclass of ParsableModel or it can have Array of models.

Get JSON String from Object

To get the JSON string from an object you just have to call JSONParserSwift.getJSON(object: NSObject) method to get the JSON.

If you want to have different keys and properties name then Conform to protocol JSONKeyCoder and implement its method key(for key: String) -> String? as given below:

class TestModel: JSONKeyCoder {

    var test: String?
    var number: Double = 0
    var boolValue: Bool = false
    var anotherTest: TestModel?
    var array: [TestModel]?
    
    public func key(for key: String) -> String? {
        switch key {
        case "boolValue":   // Properties name
            return "bool_value"     // Key in response
        case "anotherTest":
            return "another_key"
        default:
            return nil
        }
    }
}

If you want to convert the model object into JSON string then call method getJSON as given below:

// Prepare Test Model
let testModel: TestModel = TestModel()
testModel.test = "xyz"
testModel.number = 10.0
testModel.boolValue = true
    
let anotherTestModel = TestModel()
anotherTestModel.test = "abc"
anotherTestModel.number = 23
anotherTestModel.boolValue = false
    
testModel.anotherTest = anotherTestModel
testModel.array = [anotherTestModel]

do {
    // Convert into json string
    let jsonString = try JSONParserSwift.getJSON(object: testModel)
    print("Json String : \(jsonString)")
} catch {
    print(error)
}

The JSON string for the above code will be:

{
  "bool_value":true,
  "number":10,
  "test":"xyz",
  "array":[
    {
      "bool_value":false,
      "number":23,
      "test":"abc",
      "array": null,
      "another_key": null
    }
  ],
  "another_key": {
    "bool_value":false,
    "number":23,
    "test":"abc",
    "array": null,
    "another_key": null
  }
 }

Note: Currently this version do not support Optionals with Int and Array of Optional types. So prefer to use NSNumber for number related datas.

Author

See also the list of contributors who participated in this project.

License

JSONParserSwift is available under the MIT license. See the LICENSE file for more info.

You might also like...
Swift 3 framework for accessing data in Event Registry

Swift 3 framework for accessing data in Event Registry

A visual developer tool for inspecting your iOS application data structures.
A visual developer tool for inspecting your iOS application data structures.

Tree Dump Debugger A visual developer tool for inspecting your iOS application data structures. Features Inspect any data structure with only one line

Transform strings easily in Swift.

swift-string-transform Transform strings easily in Swift. Table of Contents Installation How to use Contribution Installation Swift Package Manager (R

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.
FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias. Storable protocol Actionable protocol Dispatch

A library that helps developers to easily perform file-related operations In iOS

File Operations Preview A library that helps developers to easily perform file-related operations. In iOS, We write our files mainly into three direct

Monitor iOS app version easily.

AppVersionMonitor Monitor iOS app version easily. You can get previous version and installation history. Usage To run the example project, clone the r

Vaccine is a framework that aims to make your apps immune to recompile-disease.
Vaccine is a framework that aims to make your apps immune to recompile-disease.

Vaccine Description Vaccine is a framework that aims to make your apps immune to recompile-disease. Vaccine provides a straightforward way to make you

A framework to provide logic designed to prompt users at the ideal moment for a review of your app/software

ReviewKit ReviewKit is a Swift package/framework that provides logic designed to prompt users at the ideal moment for a review of your app. At a basic

swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

Comments
  • Problem while parsing Generic objects

    Problem while parsing Generic objects

    When I tried to parse a generic object, my application got crashed and this problem has occurred while parsing an array. Here is my model class for Generic type:

    class MyModel<T>: ParsableModel {
            var responseStatus: StatusCode?
    	var responseData: T?
    	
    	override func setValue(_ value: Any?, forUndefinedKey key: String) {
    		if key == "responseData" {
    			responseData = value as? T
    		}
    	}
    }
    
    bug help wanted 
    opened by chanchalchauhan 1
Releases(1.1.4)
Owner
Mukesh
Swift | Kotlin | Go
Mukesh
Swift Xid - Xid uses MongoDB Object ID algorighm1 to generate globally unique ids with base32 serialzation to produce shorter strings

Swift Xid - Xid uses MongoDB Object ID algorighm1 to generate globally unique ids with base32 serialzation to produce shorter strings

Uditha Atukorala 0 Jun 13, 2022
A declarative, thread safe, and reentrant way to define code that should only execute at most once over the lifetime of an object.

SwiftRunOnce SwiftRunOnce allows a developer to mark a block of logic as "one-time" code – code that will execute at most once over the lifetime of an

Thumbtack 8 Aug 17, 2022
Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Apple 2k Dec 28, 2022
Parsing indeterminate types with Decodable and Either enum using Swift

Decodable + Either Parsing indeterminate types with Decodable and Either enum us

Alonso Alvarez 1 Jan 9, 2022
A Swift micro-framework to easily deal with weak references to self inside closures

WeakableSelf Context Closures are one of Swift must-have features, and Swift developers are aware of how tricky they can be when they capture the refe

Vincent Pradeilles 72 Sep 1, 2022
FeatureFlags.swift - Tools for easily defining feature flags for your projects

FeatureFlags.swift Tools for easily defining feature flags for your projects Int

Eric Rabil 1 Jan 31, 2022
WhatsNewKit enables you to easily showcase your awesome new app features.

WhatsNewKit enables you to easily showcase your awesome new app features. It's designed from the ground up to be fully customized to your needs. Featu

Sven Tiigi 2.8k Jan 3, 2023
A way to easily add Cocoapod licenses and App Version to your iOS App using the Settings Bundle

EasyAbout Requirements: cocoapods version 1.4.0 or above. Why you should use Well, it is always nice to give credit to the ones who helped you ?? Bonu

João Mourato 54 Apr 6, 2022
A Codable Undefinable type for handling JSON undefined values.

Undefinable Overview The purpose of this type is represent the JSON undefined state in Swift structs and classes. The Undefinable enum is a generic wi

David Monagle 3 Dec 18, 2022
RandomKit is a Swift framework that makes random data generation simple and easy.

RandomKit is a Swift framework that makes random data generation simple and easy. Build Status Installation Compatibility Swift Package Manager CocoaP

Nikolai Vazquez 1.5k Dec 29, 2022