Encode and decode deeply-nested data into flat Swift objects

Overview

DeepCodable: Encode and decode deeply-nested data into flat Swift objects

Have you ever gotten a response from an API that looked like this and wanted to pull out and flatten the values you care about? (This is a real response from the GitHub GraphQL API, with only the actual values changed)

{
	"data": {
		"node": {
			"content": {
				"__typename": "Example type",
				"title": "Example title"
			},
			"fieldValues": {
				"nodes": [
					{},
					{},
					{
						"name": "Example node name",
						"field": {
							"name": "Example field name"
						}
					}
				]
			}
		}
	}
}

DeepCodable lets you easily do so in Swift while maintaining type-safety, with the magic of result builders, key paths, and property wrappers:

import DeepCodable

struct GithubGraphqlResponse: DeepDecodable {
	static let codingTree = CodingTree {
		Key("data") {
			Key("node") {
				Key("content") {
					Key("__typename", containing: \._type)
					Key("title", containing: \._title)
				}

				Key("fieldValues") {
					Key("nodes", containing: \._nodes)
				}
			}
		}
	}


	struct Node: DeepDecodable {
		static let codingTree = CodingTree {
			Key("name", containing: \._name)

			Key("field", "name", containing: \._fieldName)
			/*
			The above is a "flattened" shortcut for:
			Key("field") {
				Key("name", containing: \._fieldName)
			}
			*/
		}


		@Value var name: String?
		@Value var fieldName: String?
	}

	enum TypeName: String, Decodable {
		case example = "Example type"
	}

	@Value var title: String
	@Value var nodes: [Node]
	@Value var type: TypeName
}

dump(try JSONDecoder().decode(GithubGraphqlResponse.self, from: jsonData))

Quick start

Add to your Package.Swift:

...
	dependencies: [
		...
		.package(url: "https://github.com/MPLew-is/deep-codable", branch: "main"),
	],
	targets: [
		...
		.target(
			...
			dependencies: [
				...
				.product(name: "DeepCodable", package: "deep-codable"),
			]
		),
		...
	]
]

Conform a type you want to decode to DeepDecodable by defining a coding tree representing which nodes are bound to which values:

struct DeeplyNestedResponse: DeepDecodable {
	static let codingTree = CodingTree {
		Key("topLevel") {
			Key("secondLevel") {
				Key("thirdLevel", containing: \._property)
			}
		}
	}
	/*
	Also valid is the flattened form:
	static let codingTree = CodingTree {
		Key("topLevel", "secondLevel", "thirdLevel", containing: \._property)
	}
	*/

	@Value var property: String
}
/*
Corresponding JSON would look like:
{
	"topLevel": {
		"secondLevel": {
			"thirdLevel: "{some value}"
		}
	}
}
*/

Nodes in your codingTree are made of Keys initialized one of the following ways:

  • Key("name") { /* More Keys */ }: node that don't capture values directly, but contain other nodes

    • This maps to a serialized representation like {"name": { ... } }
  • Key("name", containing: \._value): node that should be decoded into the value property

All values to decode must be wrapped with the @Value property wrapper, and the \._{name} syntax refers directly to the wrapping instance (\.{name} without the underscore refers to the actual underlying value).

Decode a value into an instance of your type:

let instance = try JSONDecoder().decode(Response.self, from: jsonData)

DeepCodable is built on top of normal Codable, so any decoder (like the property list decoder in Foundation or the excellent third-party YAML decoder, Yams) can be used to decode values.

Encoding

While decoding is probably the most common use-case for this type of nested decoding, this package also supports encoding a flat Swift struct into a deeply nested one with the same pattern:

struct DeeplyNestedRequest: DeepEncodable {
	static let codingTree = CodingTree {
		Key("topLevel") {
			Key("secondLevel") {
				Key("thirdLevel", containing: \.bareProperty)
			}

			Key("otherSecondLevel", containing: \._wrappedProperty)
		}
	}
	/*
	Also valid is the flattened form:
	static let codingTree = CodingTree {
		Key("topLevel") {
			Key("secondLevel", "thirdLevel", containing: \.bareProperty)

			Key("otherSecondLevel", containing: \._wrappedProperty)
		}
	}
	*/

	let bareProperty: String
	@Value var wrappedProperty: String
}
/*
Corresponding JSON would look like:
{
	"topLevel": {
		"secondLevel": {
			"thirdLevel: "{bareProperty}"
		},
		"otherSecondLevel": "{wrappedProperty}"
	}
}
*/

let instance: DeeplyNestedRequest = ...
let jsonData = try JSONEncoder().encode(instance)

With encoding, you don't have to use the @Value wrappers, though you can if you'd like to support decoding and encoding on the same type (in which case you can conform to DeepCodable as an alias for the two).

Key features

  • Encoding and decoding a Swift object to/from an arbitrarily complex deeply nested serialized representation without manually writing Codable implementations

  • Preservation of existing Codable behavior on the values being encoded/decoded, including custom types

    • Since DeepCodable is just a custom implementation of the Codable requirements, this also means you can nest DeepCodable objects like in the GithubGraphqlResponse example
  • When conforming to DeepEncodable or DeepDecodable, don't interfere with the opposite normal Codable implementation (Decodable/Encodable, respectively)

    • You can declare something like struct Response: DeepDecodable, Encodable { ... } and decode from a deeply nested tree, and then re-encode back to a flat structure like normal Encodable objects
  • No requirement for @Value property wrapper for types only conforming to DeepEncodable

  • Omission of the corresponding tree sections when all values at the leaves are nil

    • This makes it so trying to encode an object with a nil value doesn't result in something like {"top": {"second": {"third": null} } }
  • Flattened shortcuts using variadic parameters for long paths with no branching:

    • Key("topLevel", "secondLevel", containing: \._property) instead of Key("topLevel") { Key("secondLevel", containing: \._property) }
You might also like...
A library to turn dictionary into object and vice versa for iOS. Designed for speed!

WAMapping Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A fast mapper from JSON to NSObject Fast Simple

From JSON to Core Data and back.
From JSON to Core Data and back.

Groot Groot provides a simple way of serializing Core Data object graphs from or into JSON. It uses annotations in the Core Data model to perform the

SwiftyJSON makes it easy to deal with JSON data in Swift.

SwiftyJSON SwiftyJSON makes it easy to deal with JSON data in Swift. Platform Build Status *OS Linux Why is the typical JSON handling in Swift NOT goo

Developed with use Swift language. As a third party library used SDWebImage. JSON parsing using URLSession with TMDB API. This app provide by the Core Data structure.

Capstone Project 🎯 About Developed with use Swift language. As a third party library used SDWebImage. JSON parsing using URLSession with TMDB API. Ad

Coding Challenge using NYC JSON data

Coding Challenge using NYC JSON data This was my submission to JPMorgan's code challenge prior to an interview. It represents my solution to asyncrono

Weather - Weather app to practice using CoreLocation, fetching data from openweathermap.org API, JSON decoding, applying day\night appearance A protocol to serialize Swift structs and classes for encoding and decoding.
A protocol to serialize Swift structs and classes for encoding and decoding.

Serpent (previously known as Serializable) is a framework made for creating model objects or structs that can be easily serialized and deserialized fr

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

A fast, convenient and nonintrusive conversion framework between JSON and model. Your model class doesn't need to extend any base class. You don't need to modify any model file.

MJExtension A fast, convenient and nonintrusive conversion framework between JSON and model. 转换速度快、使用简单方便的字典转模型框架 📜 ✍🏻Release Notes: more details Co

Owner
Mike Lewis
Mike Lewis
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
An extension for Alamofire that converts JSON data into Decodable objects.

Swift 4 introduces a new Codable protocol that lets you serialize and deserialize custom data types without writing any special code and without havin

Nikita Ermolenko 749 Dec 5, 2022
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

Alibaba 4.1k Dec 29, 2022
ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects to and from JSON.

ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Tristan Himmelman 9k Jan 2, 2023
JSONExport is a desktop application for Mac OS X which enables you to export JSON objects as model classes with their associated constructors, utility methods, setters and getters in your favorite language.

JSONExport JSONExport is a desktop application for Mac OS X written in Swift. Using JSONExport you will be able to: Convert any valid JSON object to a

Ahmed Ali 4.7k Dec 30, 2022
JSONJoy - Convert JSON to Swift objects

JSONJoy Convert JSON to Swift objects. The Objective-C counterpart can be found here: JSONJoy. Parsing JSON in Swift has be likened to a trip through

Dalton 350 Oct 15, 2022
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

JSONModel - Magical Data Modeling Framework for JSON JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS

JSONModel 6.9k Dec 8, 2022
Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

JSONModel - Magical Data Modeling Framework for JSON JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS

JSONModel 6.8k Nov 19, 2021
A data visualisation tool that adds publicly available crime data from UK police forces to an interactive map.

CrimeMapper A data visualisation tool that adds publicly available crime data from UK police forces to an interactive map. Download on the App Store Y

sam woolf 11 Jul 20, 2022
Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs

Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs.

Julio Cesar Guzman Villanueva 2 Oct 6, 2022