• Stars
    star
    182
  • Rank 204,187 (Top 5 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library for loading data from a JSON API datasource.

JSONAPI - iOS

Build Status Join the chat at https://gitter.im/joshdholtz/jsonapi-ios

A library for loading data from a JSON API datasource. Parses JSON API data into models with support for linking of properties and other resources.

Quick Usage

NSDictionary *json = [self responseFromAPIRequest];
JSONAPI *jsonAPI = [JSONAPI jsonAPIWithDictionary:json];

ArticleResource *article = jsonAPI.resource;
NSLog(@"Title: %@", article.title);

For some full examples on how to use everything, please see the tests - https://github.com/joshdholtz/jsonapi-ios/blob/master/Project/JSONAPITests/JSONAPITests.m

Updates

Version Changes
1.0.7 Added meta and setMeta to JSONAPIResource and JSONAPIResourceBase (#43).
1.0.6 Improved resource parsing and added parsing of selfLinks (#35). Thanks to [ artcom](https://github.com/ artcom) for helping! Also removed the need to define setIdProperty and setSelfLinkProperty in every resource (automatically mapped in the init of JSONAPIResourceDescriptor)
1.0.5 Fix 1-to-many relationships serialization according to JSON API v1.0 (#34). Thanks to RafaelKayumov for helping!
1.0.4 Add support for empty to-one relationship according to JSON API v1.0 (#33). Thanks to RafaelKayumov for helping!
1.0.3 Add ability to map different types of objects (#32). Thanks to ealeksandrov for helping!
1.0.2 Just some bug fixes. Thanks to christianklotz for helping again!
1.0.1 Now safely checks for NSNull in the parsed JSON. Thanks to christianklotz for that fix!
1.0.0 We did it team! We are at the JSON API 1.0 final spec. Resources now use JSONAPIResourceDescriptor for more explicit definitions. HUGE thanks to jkarmstr for doing all the dirty work. Also thanks to edopelawi , BenjaminDigeon, and christianklotz for some bug fixes!
1.0.0-rc1 Rewrote core of JSONAPI and JSONAPIResource and all unit tests to be up to spec with JSON API spec 1.0.0-rc3. Removed JSONAPIResourceLinker. Added JSONAPIErrorResource
0.2.0 Added NSCopying and NSCoded to JSONAPIResource; Added JSONAPIResourceFormatter to format values before getting mapped - more info
0.1.2 JSONAPIResource IDs can either be numbers or strings (thanks danylhebreux); JSONAPIResource subclass can have mappings defined to set JSON values into properties automatically - more info
0.1.1 Fixed linked resources with links so they actually link to other linked resources
0.1.0 Initial release

Features

  • Allows resource types to be created into subclasses of JSONAPIResource
  • Set mapping for JSONAPIResource subclass to set JSON values and relationships into properties

Installation

Drop-in Classes

Clone the repository and drop in the .h and .m files from the "Classes" directory into your project.

CocoaPods

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

pod 'JSONAPI', '~> 1.0.7'

Classes/protocols

For some full examples on how to use everything, please see the tests - https://github.com/joshdholtz/jsonapi-ios/blob/master/Project/JSONAPITests/JSONAPITests.m

JSONAPI

JSONAPI parses and validates a JSON API document into a usable object. This object holds the response as an NSDictionary but provides methods to accomdate the JSON API format such as meta, errors, linked, resources, and includedResources.

JSONAPIResource

Protocol of an object that is available for JSON API serialization. When developing model classes for use with JSON-API, it is suggested that classes be derived from JSONAPIResourceBase, but that is not required. An existing model class can be adapted for JSON-API by implementing this protocol.

JSONAPIResourceBase

JSONAPIResourceBase is an object (that gets subclassed) that holds data for each resource in a JSON API document. This objects holds the "id" as ID and link for self as selfLink as well as attributes and relationships defined by descriptors (see below)

JSONAPIResourceDescriptor

+ (JSONAPIResourceDescriptor*)descriptor should be overwritten to define descriptors for mapping of JSON keys and relationships into properties of a subclassed JSONAPIResource.

Full Example

ViewController.m

NSDictionary *json = [self responseFromAPIRequest];
JSONAPI *jsonAPI = [JSONAPI jsonAPIWithDictionary:json];

ArticleResource *article = jsonAPI.resource;
NSLog(@"Title: %@", article.title);
NSLog(@"Author: %@ %@", article.author.firstName, article.author.lastName);
NSLog(@"Comment Count: %ld", article.comments.count);

ArticleResource.h

@interface ArticleResource : JSONAPIResourceBase

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) PeopleResource *author;
@property (nonatomic, strong) NSDate *date;
@property (nonatomic, strong) NSArray *comments;

@end

ArticleResource.m

@implementation ArticleResource

static JSONAPIResourceDescriptor *__descriptor = nil;

+ (JSONAPIResourceDescriptor*)descriptor {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __descriptor = [[JSONAPIResourceDescriptor alloc] initWithClass:[self class] forLinkedType:@"articles"];

        [__descriptor addProperty:@"title"];
        [__descriptor addProperty:@"date"
                 withDescription:[[JSONAPIPropertyDescriptor alloc] initWithJsonName:@"date" withFormat:[NSDateFormatter RFC3339DateFormatter]]];

        [__descriptor hasOne:[PeopleResource class] withName:@"author"];
        [__descriptor hasMany:[CommentResource class] withName:@"comments"];
    });

    return __descriptor;
}

@end

PeopleResource.h

@interface PeopleResource : JSONAPIResourceBase

@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *twitter;

@end

PeopleResource.m

@implementation PeopleResource

static JSONAPIResourceDescriptor *__descriptor = nil;

+ (JSONAPIResourceDescriptor*)descriptor {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __descriptor = [[JSONAPIResourceDescriptor alloc] initWithClass:[self class] forLinkedType:@"people"];

        [__descriptor addProperty:@"firstName" withDescription:[[JSONAPIPropertyDescriptor alloc] initWithJsonName:@"first-name"]];
        [__descriptor addProperty:@"lastName" withJsonName:@"last-name"];
        [__descriptor addProperty:@"twitter"];
    });

    return __descriptor;
}

@end

CommentResource.h

@interface CommentResource : JSONAPIResourceBase

@property (nonatomic, strong) NSString *text;
@property (nonatomic, strong) PeopleResource *author;

@end

CommentResource.m

@implementation CommentResource

static JSONAPIResourceDescriptor *__descriptor = nil;

+ (JSONAPIResourceDescriptor*)descriptor {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __descriptor = [[JSONAPIResourceDescriptor alloc] initWithClass:[self class] forLinkedType:@"comments"];

        [__descriptor addProperty:@"text" withJsonName:@"body"];

        [__descriptor hasOne:[PeopleResource class] withName:@"author"];
    });

    return __descriptor;
}

@end

Advanced

How to do custom "sub-resources" mappings

Sometimes you may have parts of a resource that need to get mapped to something more specific than just an NSDictionary. Below is an example on how to map an NSDictionary to non-JSONAPIResource models.

We are essentially creating a property descriptor that maps to a private property on the resource. We then override that properties setter and do our custom mapping there.

Resource part of JSON API Response

"attributes":{
  "title": "Something something blah blah blah"
  "image": {
    "large": "http://someimageurl.com/large",
    "medium": "http://someimageurl.com/medium",
    "small": "http://someimageurl.com/small"
  }
}

ArticleResource.h

@interface ArticleResource : JSONAPIResourceBase

@property (nonatomic, strong) NSString *title;

// The properties we are pulling out of a a "images" dictionary
@property (nonatomic, storng) NSString *largeImageUrl;
@property (nonatomic, storng) NSString *mediumImageUrl;
@property (nonatomic, storng) NSString *smallImageUrl;

@end

ArticleResource.m

@interface ArticleResource()

// Private variable used to store raw NSDictionary
// We will override the setter and set our custom properties there
@property (nonatomic, strong) NSDictionary *rawImage;

@end

@implementation ArticleResource

static JSONAPIResourceDescriptor *__descriptor = nil;

+ (JSONAPIResourceDescriptor*)descriptor {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __descriptor = [[JSONAPIResourceDescriptor alloc] initWithClass:[self class] forLinkedType:@"articles"];

        [__descriptor addProperty:@"title"];
        [__descriptor addProperty:@"rawImage" withDescription:[[JSONAPIPropertyDescriptor alloc] initWithJsonName:@"image"]];

    });

    return __descriptor;
}

- (void)setRawImage:(NSDictionary*)rawImage {
  _rawImage = rawImage;

  // Pulling the large, medium, and small urls out when
  // this property gets set by the JSON API parser
  _largeImageUrl = _rawImage[@"large"];
  _mediumImageUrl = _rawImage[@"medium"];
  _smallImageUrl = _rawImage[@"small"];
}

@end

Author

Josh Holtz, [email protected], @joshdholtz

License

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

More Repositories

1

DeckUI

Swift DSL for writing slide decks in Xcode
Swift
589
star
2

Sentry-Android

[Deprecated] Use official "raven-java" library
Java
180
star
3

jenkins-slack-command

Start a build in Jenkins using a Slack Command
Ruby
55
star
4

wassup

Easily scriptable terminal dashboard
Ruby
39
star
5

crunchygif

EZPZ VIDEO TO GIF CREATOR
Swift
34
star
6

fastlane-plugin-github_action

A plugin for setting up fastlane on GitHub Actions
Ruby
33
star
7

CropImageView

Super easy component for Android to crop an image
Java
33
star
8

connectkit-examples

21
star
9

NSDate-MinimalTimeAgo

NSDate category for very minimal style time ago
Objective-C
17
star
10

exportation

CLI tool of easy exporting/encrypting, and decrypting/importing of certificates and private keys
Ruby
17
star
11

ios-promises

[Deprecated] [Super no longer maintained] Objective-C implementation of jQuery-ish promises
Objective-C
17
star
12

LayoutOfRelativity

iOS relative layout rules
Objective-C
9
star
13

Notables-Swift

Protocol extensions for common NSNotifications for the lazy (me)
Swift
9
star
14

fastlane-plugin-queue

Queues for fastlane - with web interface 😱
Ruby
9
star
15

ionic-configurator

Configure Ionic (Cordova) config.xml files for individual environments using Mustache templating
JavaScript
8
star
16

swift-webframeworks-docker

Docker containers used for spinning up different Swift web frameworks
Swift
8
star
17

dotenv_to_ci

The laziest way to transfer environment variables from a .env file to a CI provider πŸ‘‹
Ruby
8
star
18

dotfiles

Vim Script
7
star
19

fastlane-plugin-rename_android_package

Ruby
7
star
20

wassup-swift

Wassup is a flexible and customizable dashboard for showing GitHub data.
Swift
7
star
21

ios-swift-test

Swift
7
star
22

chrome-circle-pr

Send a parameterized build to your CircleCI project from the push of a button while viewing your Pull Request on Github
JavaScript
7
star
23

fastlane-plugin-android_keystore

Generate an Android keystore file
Ruby
6
star
24

CircleShadowImageView

iOS UIImageView subclass for making a circle image with a shadow
Objective-C
6
star
25

ecto-lazy-float

Ecto.LazyFloat - An Ecto.Float that accepts binary and integers
Elixir
6
star
26

jenkins-ironmq

Start a Jenkins job from an IronMQ message
Ruby
5
star
27

Protocol-Android

Java
5
star
28

JHSidebar

Objective-C
5
star
29

JHTableViewPullRefresh

Objective-C
3
star
30

RestCat

A RESTful library for iOS
Objective-C
3
star
31

hubby

Ruby
3
star
32

wassup-swift-releases

3
star
33

grandpa-kennys-fishing-adventure-early-access

3
star
34

raven-rust

Rust
2
star
35

circleci-orbs

CircleCI Orbs that make my life easier 😊
2
star
36

html-pager

HTML Pager
Ruby
2
star
37

fastlane-plugin-revenuecat

A fastlane plugin for interacting with the RevenueCat Developer API
Ruby
2
star
38

Trajectory

Android routing library
Java
2
star
39

PicPick

Java
2
star
40

shift

Application backend
JavaScript
2
star
41

liveedutv-obs-overlay

A LiveEdu.tv overlay for use in OBS (or other streaming application)
HTML
2
star
42

fastlane-plugin-install_android

Ruby
2
star
43

homeboy

JavaScript
1
star
44

joshdholtz

Ruby
1
star
45

slack-receipt-bot

Elixir
1
star
46

fastlane-plugin-bomb_emoji

πŸ’£ all the emojis in the fastlane output
Ruby
1
star
47

SlideyMenuGuy

Objective-C
1
star
48

NProgressIsh-iOS

NProgress like style progress bar for iOS
Objective-C
1
star
49

raycast-revenuecat

TypeScript
1
star
50

climbon-api

Swift
1
star
51

cupcakegram-ios

Swift
1
star
52

Protocol

Protocol
Objective-C
1
star
53

Protocol-iOS

Objective-C
1
star
54

JHAccordion

Objective-C
1
star
55

NavBarSwipeTitle

Objective-C
1
star
56

old_harmonic

A Swift library for loading JSON objects and arrays into Swift objects
Swift
1
star
57

yeah-buddy

JavaScript
1
star
58

ionic-configurator-example

CSS
1
star
59

star-wars-a-new-app

Swift
1
star
60

fastlane-plugin-testfairy

Upload an IPA to TestFairy
Ruby
1
star
61

Rekt-Swift

Functional approach to altering CGRect
Swift
1
star
62

Mockery-iOS

iOS Web Framework?? Not sure what to call this yet
Objective-C
1
star
63

KSCrash-Locking-Up-In-Swift-Example

KSCrash locks up in Swift but not in Objective-C (both example included)
C
1
star
64

storekit-config-file-demo

Demo app on how to use StoreKit Config File with RevenueCat and StoreKit 2
Swift
1
star
65

JustTransloadit-iOS

A simple to use Transloadit library
Objective-C
1
star
66

CLGeocoder-DoubleLookup

CLGeocoder+DoubleLookup - Give address components, get more address components back (like zip code)
Objective-C
1
star
67

test-repo-for-fastlane-plugin-github_action

Ruby
1
star
68

altconf-fastlane-best-practices

AltConf Lab Session Slides - fastlane Best Practices
CSS
1
star