The better way to deal with JSON in Objective-C (inspired by SwiftyJSON)

Overview

NSTEasyJSON

Inpired by SwiftyJSON. NSTEasyJSON makes it easy to deal with JSON data in Objective-C.

  1. Why is the typical JSON handling in Objective-C NOT good
  2. Requirements
  3. Integration
  4. Usage

Why is the typical JSON handling in Objective-C NOT good?

Objective-C is not very strict about types, but even without strictness we cannot save time because we have to check types ourselves for safety.

Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Objective-C (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline).

The code would look like this:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSString *user = dictionary[@"user"];
// Now we got the username
// But is it NSString for sure?

We got the username in 2 lines, but will JSON always be NSDictionary? Can API send null as value for user key? To be safe we need to add some lines:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if (![dictionary isKindOfClass:[NSDictionary class]]) {
	// Print the error
}
NSString *user = dictionary[@"user"];
if (![user isKindOfClass:[NSString class]]) {
 	// Print the error
}
// There's our username

It's simple, but it boilerplate for sure!

With NSTEasyJSON all you have to do is:

NSTEasyJSON *JSON = [NSTEasyJSON withData:dataFromNetworking];
NSString *userName = JSON[0]["user"]["name"].string;
// Now you got your value

And don't worry about the NSNull, out of bounds or other unexpected things. It's done for you automatically.

Requirements

  • iOS 7.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+
  • Xcode 7

Integration

CocoaPods (iOS 7+, OS X 10.9+)

You can use CocoaPods to install NSTEasyJSON by adding it to your Podfile:

platform :ios, '7.0'

target 'MyApp' do
	pod 'NSTEasyJSON'
end

Manually (iOS 7+, OS X 10.9+)

To use this library in your project manually you may:

  1. for Projects, just drag NSTEasyJSON.{h,m} to the project tree
  2. for Workspaces, include the whole NSTEasyJSON.xcodeproj

Usage

Initialization

#import "NSTEasyJSON.h"
NSTEasyJSON *JSON = [NSTEasyJSON withData:dataFromNetworking];
NSTEasyJSON *JSON = [NSTEasyJSON withObject:jsonObjectArrayOrMaybeDictionary];

Subscript

// Getting a double from a JSON Array
double name = JSON[0].doubleValue;
// Getting a string from a JSON Dictionary
NSString *name = json["name"].stringValue;

Optional getter

// NSNumber
NSNumber *number = JSON[@"user"][@"favourites_count"].number;
// NSString
NSString *string = JSON[@"user"][@"name"].string;
...

Non-optional getter

Non-optional getters are named xxxValue

// If not a Number or nil, return 0
NSNumber *number = JSON[@"user"][@"favourites_count"].numberValue;
// If not a String or nil, return ""
NSString *string = JSON[@"user"][@"name"].stringValue;
// If not an Array or nil, return @[]
NSArray *list = JSON[@"list"].arrayValue;
// If not a Dictionary or nil, return @{}
NSDictionary *dictionary = JSON[@"user"].dictionaryValue;
You might also like...
Functional JSON Parser - Linux Ready
Functional JSON Parser - Linux Ready

Functional JSON Parser Feature Linux Ready Type-safe JSON parsing Functional value transformation Easy to parse nested value Dependency free No define

Arrow  🏹 Parse JSON with style
Arrow 🏹 Parse JSON with style

Arrow 🏹 Parse JSON with style

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

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

Freddy - A reusable framework for parsing JSON in Swift.
Freddy - A reusable framework for parsing JSON in Swift.

Why Freddy? Parsing JSON elegantly and safely can be hard, but Freddy is here to help. Freddy is a reusable framework for parsing JSON in Swift. It ha

[Deprecated] A shiny JSON parsing library in Swift :sparkles: Loved by many from 2015-2021
[Deprecated] A shiny JSON parsing library in Swift :sparkles: Loved by many from 2015-2021

🚨 Deprecation Notice 🚨 Gloss has been deprecated in favor of Swift's Codable framework. The existing Gloss source is not going away, however updates

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

Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift.

Himotoki Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift. This library is highly inspired by the popular Swift JSON parsin

JASON is a faster JSON deserializer written in Swift.
JASON is a faster JSON deserializer written in Swift.

JASON is a faster JSON deserializer written in Swift. JASON is the best framework we found to manage JSON at Swapcard. This is by far the fastest and

Comments
  • Useful stability fix

    Useful stability fix

    Hi,

    I'm using your great library and it looks like that the data I'm getting from server can be incosistent, so if the server returns no data, the app crashes in "+ (nonnull instancetype)withData:(nullable NSData *)data".

    I've made the simple fix for that issue and am sharing it here with you: id object = [NSJSONSerialization JSONObjectWithData:data ? data : [NSData data] options:NSJSONReadingAllowFragments error:&error];

    opened by duke4e 2
  • Add JSONArray and JSONDictionary

    Add JSONArray and JSONDictionary

    It will be good to support such things:

    NSDictionary *dictionary = @{@"array":@[@{@"key":@"value"}]};
    NSTEasyJSON *JSON = [NSTEasyJSON withObject:someDictionary];
    for (NSTEasyJSON *arrayItemJSON in JSON[@"array"].JSONArray) {
        NSString *value = arrayItemJSON[@"key"].string;
    }
    
    enhancement 
    opened by bernikovich 1
Releases(1.0.6)
Owner
Timur Bernikovich
iOS Developer
Timur Bernikovich
SwiftyJSON decoder for Codable

SwiftyJSONDecoder 功能 继承自 JSONDecoder,在标准库源码基础上做了改动,与其主要区别如下 使用 SwiftyJSON 解析数据,使用其类型兼容功能 废弃 nonConformingFloatDecodingStrategy 属性设置,Double 及 Float 默认解

null 2 Aug 10, 2022
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
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
This framework implements a strict JSON parser and generator in Objective-C.

SBJson 5 Chunk-based JSON parsing and generation in Objective-C. Overview SBJson's number one feature is stream/chunk-based operation. Feed the parser

null 3.8k Jan 5, 2023
Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend. Using Argo

thoughtbot, inc. 3.5k Dec 20, 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