JSONCodable is also available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'JSONCodableType'
Usage
Encoding JSONCodable values from a dictionary:
let dictionary: [String: JSONCodable] = [
"null": .null,
"integer": 1,
"number": 1.1,
"boolean": true,
"string": "test",
"array": ["item1", "item2"],
"dictionary": ["key1": "value1", "key2": "value2"]
]
let data = try JSONEncoder().encode(dictionary)
Decoding JSONCodable values:
let jsonString = """
{
"null": null,
"integer": 1,
"number": 1.1,
"boolean": true,
"string": "test",
"array": ["item1", "item2"],
"dictionary": { "key1": "value1", "key2": "value2" }
}
"""
let data = jsonString.data(using: .utf8)!
let dictionary = try JSONDecoder().decode([String: JSONCodable].self, from: data)
let anyDictionary: [String: Any] = jsonCodableDictionary.mapAnyValues()
Working with custom Codable types:
struct User: Codable {
let name: String
let meta: [String: JSONCodable]
}
let user = User(name: "Test", meta: ["string": "value", "integer": 1])
let data = try JSONEncoder().encode(user)
let decodedUser = try JSONDecoder().decode(User.self, from: data)
JSONCodable is a lightweight library for decoding/encoding all basic JSON types in a type-safe manner.
[String: JSONCodable]
to[String: Any]
and backInstallation
To integrate using Apple’s Swift package manager, add the following as a dependency to your Package.swift:
JSONCodable is also available through CocoaPods. To install it, simply add the following line to your Podfile:
Usage
Encoding
JSONCodable
values from a dictionary:Decoding
JSONCodable
values:Working with custom
Codable
types: