FreeformJSON: Type-safe freeform JSON data structure with Codable support for Swift
FreeformJSON is a tiny data structure that allows you to create and/or access freeform JSON data in a type safe manner, while still enjoying the benefits of the Codable protocol. This can be useful if there are parts of your model that you want to have access to, but don't want the overhead of having a class
/struct
for it.
Examples
Codable
data structures
Use inside other import FreeformJSON
struct Post: Codable {
let name: String
let embeddedContent: JSON
}
...
let link = post.embeddedContent["origin"]["link"].string
Create from literal values
let post: JSON = [
"name": "My Post",
"rating": 4,
"hidden": false,
"tags": ["tag1", "tag2"]
]
Encodable
type
Create from any struct Post: Encodable {
let name: String
let rating: Double
let hidden: Bool
let tags: [String]
}
let post = Post(name: "My Post", rating: 4.0, hidden: false, tags: ["tag1", "tag2"])
let postJson = try JSON.fromEncodable(post)
let name = post["name"].string // Optional("My Post")
Safe or raw access to properties
let name = post["name"].string // Optional("My Post")
let notAString = post["rating"].string // nil
let nonExisting = post["nonExisting"].string // nil
let tag = post["tags"][0] // Optional("tag1")
let rawTags = post["tags"].rawValue! as! [String] // ["tag1", "tag2"]
Requirements
FreeformJSON is compatible with Swift 4.x and later. All Apple platforms are supported:
- iOS 9.0+
- macOS 10.9+
- watchOS 2.0+
- tvOS 9.0+
Installation
Single file
Just drop JSON.swift
anywhere in your own project.
Framework
Download the repo, drag FreeformJSON.xcodeproj
into your own project and link the appropriate target for your platform.
CocoaPods
Inside your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'TargetName' do
use_frameworks!
pod 'FreeformJSON'
end
Carthage
Inside your Cartfile
:
github "fabiorodella/FreeformJSON"
Swift Package Manager
Inside your Package.swift
:
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "TargetName",
dependencies: [
.package(url: "https://github.com/fabiorodella/FreeformJSON.git", from: "1.0.0"),
],
targets: [
.target(
name: "TargetName",
dependencies: ["FreeformJSON"]),
]
)