• Stars
    star
    249
  • Rank 162,051 (Top 4 %)
  • Language
    Swift
  • Created about 8 years ago

Reviews

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

Repository Details

🧱 A JSON decoding/encoding library that handles optimistically or strictly.

Do you need to handle the root cause of failure in decoding JSON?

We often process the value as a default value if it could not be decoded from JSON. (Recovering with a default value)
However, doing that might cause a serious problem and hide the actual root cause in the app.
Recovering with a default value is not a bad choice, it's important to know the JSON represents unexpected shape or value before recovering.

let json: JSON

do {
  self.id = try json.next("id").getString()
} catch {
  print(error)
  // We can know why decoding failed from error.
  // Not found "id" or "id" found but it was not `string` or something else.
  // that's why here recover the value to fill `self.id`
  self.id = "unknown"
}

JAYSON provides 2 ways of accessing to JSON object.

  1. Easy access (with dynamic-member-lookup)
let urlString: String? = json[3]?.shot?.images?.hidpi_image?.string
  1. Strict access (with dynamic-member-lookup)

We can know where error was caused. (with JSONError)

let id: String = try json
    .next(0)
    .next("id")
    .getString()

JAYSON

Build Status FOSSA Status Version License Platform Carthage compatible

Strict and Scalable JSON library. And also supports dynamicMemberLookup

Requirements

Swift 5+ iOS📱, watchOS⌚️, tvOS📺, macOS🖥, Linux

Usage

Read JSON

Easy Access

let urlString: String? = json[3]?["shot"]?["images"]?["hidpi_image"]?.string

Strict Access (try-catch)

if the value does not exist, throw JSONError
Failed location can be known from JSONError

Get Value (String, Bool, Number)

let id: String = try json
    .next(0)
    .next("id")
    .getString()

Using dynamicMemberLookup

let id: String = try json
    .next(0)
    .next(\.id)
    .getString()

Get Value with Decoder (Custom Object)

Using the Decoder can be transformed in a custom object. And, throwable

let imageURL: URL = try json
    .next(0)
    .next("image")
    .next("hidpi_image")
    .get {
        URL.init(string: try $0.getString())!
    }

General Getter

Strict getters

extension JSON {
    public func getDictionary() throws -> [String : JSON]
    public func getArray() throws -> [JSON]
    public func getNumber() throws -> NSNumber
    public func getInt() throws -> Int
    public func getInt8() throws -> Int8
    public func getInt16() throws -> Int16
    public func getInt32() throws -> Int32
    public func getInt64() throws -> Int64
    public func getUInt() throws -> UInt
    public func getUInt8() throws -> UInt8
    public func getUInt16() throws -> UInt16
    public func getUInt32() throws -> UInt32
    public func getUInt64() throws -> UInt64
    public func getString() throws -> String
    public func getBool() throws -> Bool
    public func getFloat() throws -> Float
    public func getDouble() throws -> Double
}

///
extension JSON {
    public func get<T>(_ s: (JSON) throws -> T) rethrows -> T
}

Optional Read-only properties😁

extension JSON {
    public var dictionary: [String : Any]? { get }
    public var array: [Any]? { get }
    public var string: String? { get }
    public var number: NSNumber? { get }
    public var double: Double? { get }
    public var float: Float? { get }
    public var int: Int? { get }
    public var uInt: UInt? { get }
    public var int8: Int8? { get }
    public var uInt8: UInt8? { get }
    public var int16: Int16? { get }
    public var uInt16: UInt16? { get }
    public var int32: Int32? { get }
    public var uInt32: UInt32? { get }
    public var int64: Int64? { get }
    public var uInt64: UInt64? { get }
    public var bool: Bool? { get }
}

Initialize JSON

let jsonData: Data = ...
let json = try JSON(data: jsonData)
let jsonData: Data
let json: Any = try JSONSerialization.jsonObject(with: data, options: [])
let json = try JSON(any: json)
let userInfo: [AnyHashable: Any]
let json = try JSON(any: json)
let objects: [Any]
let json = try JSON(any: json)

In the case of the following try it is not required.

let object: [String : JSON]
let json = JSON(object)
let object: [JSON]
let json = JSON(object)
let object: [JSONWritableType]
let json = JSON(object)
let object: [String : JSONWritableType]
let json = JSON(object)

Get current path (Debugging information.)

let path = try json
    .next(0)
    .next("image")
    .next("hidpi_image")
    .currentPath()

// path => "[0]["image"]["hidpi_image"]"

JSONError

If you have access that does not exist key, throw JSONError.

public enum JSONError: Error {
  case notFoundKey(key: String, json: JSON)
  case notFoundIndex(index: Int, json: JSON)
  case failedToGetString(source: Any, json: JSON)
  case failedToGetBool(source: Any, json: JSON)
  case failedToGetNumber(source: Any, json: JSON)
  case failedToGetArray(source: Any, json: JSON)
  case failedToGetDictionary(source: Any, json: JSON)
  case decodeError(source: Any, json: JSON, decodeError: Error)
  case invalidJSONObject
}

example:

do {
  let urlString: String = try json
    .next("shots")
    .next(0)
    .next("user")
    .next("profile_image")
    .next("foo") // ‼️ throw
    .getString()
} catch {
   print(error)
}

Output jsonError

notFoundKey("foo",
json
Path: Root->["shots"][0]["user"]["profile_image"]
SourceType: dictionary

Source:
{
    large = "https://...";
    medium = "https://...";
    small = "https://...";
})

Go Back JSON hierarchy

try json
    .next(0)
    .next("image")
    .back() // <---
    .next("image")
    .next("hidpi_image")

Import Example (dribbble API)

let json = try! JSON(data)

struct Shot {
    let id: Int
    let title: String
    let width: Int
    let height: Int
    let hidpiImageURLString: String?
    let normalImageURLString: String
    let teaserImageURLString: String
}

do {
    let shots: [Shot] = try json.getArray().map { json -> Shot in

        let imagesjson = try json.next("images")

        return Shot(
            id: try json.next("id").getInt(),
            title: try json.next("title").getString(),
            width: try json.next("width").getInt(),
            height: try json.next("height").getInt(),
            hidpiImageURLString: try? imagesjson.next("hidpi").getString(),
            normalImageURLString: try imagesjson.next("normal").getString(),
            teaserImageURLString: try imagesjson.next("teaser").getString()
        )
    }
    print(shots)
} catch {
    print(error)
}

Write JSON

var json = JSON()
json["id"] = 18737649
json["active"] = true
json["name"] = "muukii"

var images = [String:JSON]()
images["large"] = "http://...foo"
images["medium"] = "http://...bar"
images["small"] = "http://...fuzz"

json["images"] = JSON(images)

let data = try json.data(options: .prettyPrinted)

-> data

{
  "name" : "muukii",
  "active" : true,
  "id" : 18737649,
  "images" : {
    "large" : "http:\/\/...foo",
    "small" : "http:\/\/...fuzz",
    "medium" : "http:\/\/...bar"
  }
}

json Convertible Examples

var json = JSON()

json["String"] = "String"
json["NSString"] = JSON("NSString" as NSString)
json["NSNumber"] = NSNumber(value: 0)
json["Int"] = 64
json["Int8"] = JSON(8 as Int8)
json["Int16"] = JSON(16 as Int16)
json["Int32"] = JSON(32 as Int32)
json["Int64"] = JSON(64 as Int64)

json["UInt"] = JSON(64 as UInt)
json["UInt8"] = JSON(8 as UInt8)
json["UInt16"] = JSON(16 as UInt16)
json["UInt32"] = JSON(32 as UInt32)
json["UInt64"] = JSON(64 as UInt64)

json["Bool_true"] = true
json["Bool_false"] = false

json["Float"] = JSON(1.0 / 3.0 as Float)
json["Double"] = JSON(1.0 / 3.0 as Double)
json["CGFloat"] = JSON(1.0 / 3.0 as CGFloat)

Installation

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

pod "JAYSON"

Author

muukii, [email protected]

License

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

FOSSA Status

More Repositories

1

NextGrowingTextView

📝 The next in the generations of 'growing textviews' optimized for iOS 8 and above.
Swift
1,623
star
2

DataSources

💾 🔜📱 Type-safe data-driven CollectionView, TableView Framework. (We can also use ASCollectionNode)
Swift
556
star
3

Rideau

🎪 Rideau is a drawer UI similar to what Apple's apps use. (e.g Maps, Shortcuts) Supports multiple snap points
Swift
473
star
4

StackScrollView

📋 iOS Form UI Builder in Swift (powered by UICollectionView)
Swift
402
star
5

MondrianLayout

🏗 A way to build AutoLayout rapidly than using InterfaceBuilder(XIB, Storyboard) in iOS.
Swift
145
star
6

PrecisionLevelSlider

PrecisionLevelSlider
Swift
129
star
7

CPKenburnsView

CPKenburnsView is ken burns effect
Objective-C
105
star
8

ZoomImageView

UI component library to expand the photo, such as Apple's Photos app
Swift
97
star
9

LightRoom

Easy Chaining ImageFilter with CoreImage 📸
Swift
94
star
10

CPKenburnsSlideshowView

Inspired by Hey Day
Objective-C
69
star
11

Bulk

👨‍💻 Bulk is a library for buffering the objects. Pipeline(Sink) receives the object and emits the object bulked.
Swift
61
star
12

FluidInterfaceKit

🌧 A framework that provides the advanced infrastructure for your iPhone apps
Swift
53
star
13

TypedTextAttributes

🖍 The Library Creating Text Attributes with Type-Safety
Swift
49
star
14

ColorCube

Create CubeData for CIColorCube from LUT image.
Swift
30
star
15

OneStore

📕A single value proxy for NSUserDefaults, with clean API.
Swift
27
star
16

cocoapods-frost

📦 A plugin for CocoaPods that creates XCFramework(for internal distribution) for speeding up build time.
Ruby
25
star
17

jackhammer-syntax

Dark and Bright Syntax Theme
CSS
21
star
18

FluidPresentation

🍞 [Beta] A view controller that can unwind like presentation and navigation.
Swift
20
star
19

iOS7-Blur

Fast UIView Screenshot and BlurEffect
Objective-C
20
star
20

TextAttributesUtil

Quickly create NSAttributedString with TextAttributes
Swift
15
star
21

Presenter

Screen transition with safe and clean code.
Swift
14
star
22

Warehouse

Easy NSFileManager
Swift
13
star
23

MatchedTransition

[Used in Pairs] A primitive stuff to do transition
Swift
11
star
24

Bureau

An easy way to use input view to display custom-view on iOS UIKit
Swift
11
star
25

Drip.app

A photo editor app
Swift
11
star
26

chglog

🪵 A changelog generator that regarding pulls and specified commits.
TypeScript
10
star
27

BoxLayout

[WIP] SwiftUI's interface like AutoLayout DSL
Swift
10
star
28

Sample.UmbrellaFramework

Swift
10
star
29

ModernUpperNotificationView

ModernUpperNotificationView is simple notification view - powered by
Swift
10
star
30

Capturer

📸 A wrapper for AVCaptureSession - The way easier to use the Camera.
Swift
9
star
31

swiftui-GestureVelocity

In SwiftUI, a property-wrapper provides velocity in pt/s from gesture
Swift
9
star
32

MusicalScaleKit

Generate notes on Musical Scale
Swift
9
star
33

Grain

A data serialization template language in Swift
Swift
8
star
34

AutoresizingTableCollectionView

SampleCode Autoresizing Cells
Swift
7
star
35

ResultBuilderKit

Set of result builder
Swift
6
star
36

TextureBook

The sample codes using Texture.
Swift
6
star
37

CircleWaveAnimation-Playground

Swift
6
star
38

swiftui-WrapLayout

A custom layout built on top of SwiftUI's Layout API that lays elements out in multiple lines. Similar to flex-wrap in CSS, CollectionViewFlowLayout.
Swift
6
star
39

swiftui-AsyncMultiplexImage

Swift
5
star
40

RxFuture

🛸A library to provide Future/Promise pattern API that is backed by RxSwift.
Swift
5
star
41

ViewFinder

Find the UI Component by accessibilityIdentifier from AppDelegate.window
Swift
5
star
42

CompositionKit

A collection of components to build composed component
Swift
5
star
43

Bound

⛓The Bound is a library for building iOS view transitions using UIViewPropertyAnimator.
Swift
5
star
44

ConcurrencyContinuationReproduce

[FB11707587] **`withCheckedContinuation`'s body will run on background thread in case of starting from main-actor.**.
Swift
5
star
45

Lab.swift

Just my playground space for learning Swift
Swift
5
star
46

TransitionPatch

Declarative sequence for converting value.
Swift
4
star
47

Unwrap

let _self = try self.unwrapped()
Swift
4
star
48

ViewSizeCalculator

Calculate UIView size
Swift
4
star
49

YogaBasedLayout

[WIP] Mondrian provides the layout interface like TetureGroup/Texture with high-optimized layout engine facebook/yoga flexbox implementation.
Swift
4
star
50

L10n.swift

Generate Localizable.strings from yaml (Work in progress)
Swift
4
star
51

Realm-EasyBackground

C++
4
star
52

Try.Umbrella

Swift
4
star
53

Play.ThrowBox

Trial about UISpringTimingParameters with UIViewPropertyAnimator
Swift
3
star
54

ColorGen

Generate .clr file from json
Objective-C
3
star
55

Swift-binary-size

Swift
3
star
56

RxAssert

Check element in Stream
Swift
3
star
57

APNsClient

[WIP] A desktop application to send a apns push with HTTP/2 based API. (Using VergeStore, Redux Arch)
Swift
3
star
58

BalloonUI

Swift
3
star
59

UpperNotificationController

UpperNotificationController is core for appear notification to upper on app screen
Swift
3
star
60

iOS15-UIRefreshControl-issue-reproduction

Swift
2
star
61

PhotosPicker

Swift
2
star
62

Simctl

Desktop Application Control Xcode's Simulator
JavaScript
2
star
63

UpperNotificationView

UpperNotificaitonView
Objective-C
2
star
64

dotfiles

Python
2
star
65

actions-xcode-install-simulator

Installs simulator runtime for Xcode development
2
star
66

swagger-ejs

HTML
2
star
67

RealmSwiftSupport

WIP
Swift
2
star
68

MuukiiPhoto

Swift
2
star
69

cocoapods-xcframework

[Not working] Integrates pods in form of prebuilt xcframeworks conveniently, reducing compile time
Ruby
2
star
70

RequestKit

Swift
2
star
71

playground

Welcome to my yard.
Swift
2
star
72

PhotosProvider

Swift
2
star
73

Play.RunLoopWaiter

Swift
2
star
74

issue-texture-swiftui-preview

reproduction for texture on swiftui preview
Swift
1
star
75

Garage

Swift
1
star
76

GitCommand.swift

Git-Command builder for Swift
Swift
1
star
77

ModuleKit

Tool for resource loading on Swift iOS Module (NSBundle(forClass: self.dynamicType)
Swift
1
star
78

ios-project-template

Swift
1
star
79

Reveal2Loader

Objective-C
1
star
80

atom-fruits

CSS
1
star
81

MBlurPopImageVIew

Objective-C
1
star
82

InputFieldView

Swift
1
star
83

EmbeddedStringsKit

Swift
1
star
84

Descriptors

Swift
1
star
85

RunLoopWaiter

Swift
1
star
86

ApplicationMonitor

Monitor life-cycle : Application-UIKit.
Swift
1
star
87

electron-pusher

The Desktop Application Sending Apple Push Notification
JavaScript
1
star
88

GeometryKit

Calculating geometry in CoreGraphics
Swift
1
star
89

framework-swift-interfaces

1
star
90

actions-xcode-create-simulator

Creates an iOS Simulator specified version and device
1
star
91

PlayTexture

The catalog of UI that laid out with Texture
Swift
1
star
92

RxSwiftPractice

Swift
1
star
93

PortalView

Swift
1
star
94

Quartz-Composer

1
star
95

Lightroom-Presets

1
star
96

Atom-Neka-Syntax

CSS
1
star
97

FigJam-Schema

TypeScript
1
star
98

figma-JSONSchema

TypeScript
1
star
99

IgnoreNilAssignmentOperator

value =? nil // This does not insert
Swift
1
star
100

RxUnsplashSource

https://source.unsplash.com/
Swift
1
star