swift-json
is a dynamic wrapper around JSON decoders that uses @dynamicMemberLookup
and @dynamicCallable
features to access values from JSON data.
This is useful for accessing specific values from JSON data when you want to skip over unwanted boilerplate abstractions. For instance, we have the following fragment, and the longitude value is all we are interested in:
let data = """
{
"address": {
"city": "Stockholm",
"geo": {
"latitude": 59.2,
"longitude": 18.04
}
}
}
"""
.data(using: .utf8)!
To achieve this with JSONDecoder
, we need to populate the following structs:
import Foundation
struct Response: Decodable {
let address: Address
}
struct Address: Decodable {
let geo: Geo
}
struct Geo: Decodable {
let longitude: Double
}
let longitude = try JSONDecoder()
.decode(Response.self, from: data)
.address
.geo
.longitude
// Prints 18.04
print(longitude)
With swift-json
it would be:
import JSON
let longitude: Double = try JSON(data)
.address
.geo
.longitude
// Prints 18.04
print(longitude)
.package(url: "https://github.com/nchlscs/swift-json", from: "0.3.0")
link |
Stars: 0 |
Last commit: 3 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics