I am trying to parse a nested JSON string. Below are the JSON string, the structure I've created, and the JSON decoding function I am using. I am able to access the name member easily, but am having trouble with the other items. For instance, in my employeeData object, how can I access Sam's hours from the 3/31/2018 record?
Thank you in advance.
JSON String
[
{
"name": "John",
"records": [
{
"reportDate": "2018-06-30",
"hours": 204,
"billable": 32844
},
{
"reportDate": "2018-03-31",
"hours": 234,
"billable": 37715
}
]
},
{
"name": "Sam",
"records": [
{
"reportDate": "2018-06-30",
"hours": 187,
"billable": 13883
},
{
"reportDate": "2018-03-31",
"hours": 176,
"billable": 13467
}
]
}
]
Struct
struct Employee : Decodable {
let name : String?
let records : [Record]
private enum CodingKeys: String, CodingKey {
case name = "name"
case records
}
struct Record : Decodable {
let reportDate : String?
let hours : Int?
let billable : Int?
private enum CodingKeys: String, CodingKey {
case reportDate = "reportDate"
case hours = "hours"
case billable = "billable"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
reportDate = try values.decodeIfPresent(String.self, forKey: .reportDate)
hours = try values.decodeIfPresent(Int.self, forKey: .hours)
billable = try values.decodeIfPresent(Int.self, forKey: .billable)
}
}
}
JSON Decoding fiction
func downloadJSON( completed:#escaping ()->()){
guard let qurl = URL("https://website.com") else { return }
URLSession.shared.dataTask(with: qurl) { (data, response, error) in
if error == nil {
do{
self.employeeData = try JSONDecoder().decode([Employee].self, from: data!)
DispatchQueue.main.async{ completed() }
} catch { print("JSON Error") }
}
}.resume()
}
First of all you can reduce your structs to
struct Employee : Decodable {
let name : String
let records : [Record]
struct Record : Decodable {
let reportDate : String
let hours : Int
let billable : Int
}
}
The CodingKeys and the initializer are created by the protocol extension.
To get the inner data you need two loops
for employee in self.employeeData {
print(employee.name)
for record in employee.records {
print(record.reportDate)
print(record.hours)
}
}
To get Sam's hours at 2018-03-31 you could filter the data with
if let sam = self.employeeData.first(where: {$0.name == "Sam"}),
let date = sam.records.first(where: {$0.reportDate == "2018-03-31"}) {
print(date.hours)
}
Related
I have an API response below. The "USER_LIST" response is different based on the value of "DATA_NUM". The problem I have is when the "DATA_NUM" is "0", it returns an empty string AND when "DATA_NUM" is "1", the "USER_LIST" returns both object and an empty string so that I can't decode with a model below. I want to construct a model that's suitable for every case regardless of the value of the "DATA_NUM".
How can I achieve this? Thanks in advance.
API response
// when "DATA_NUM": "0"
{
"RESPONSE": {
"DATA_NUM": "0",
"USER_LIST": ""
}
}
// when "DATA_NUM": "1"
{
"RESPONSE": {
"DATA_NUM": "1",
"USER_LIST": [
{
"USER_NAME": "Jason",
"USER_AGE": "30",
"ID": "12345"
},
""
]
}
}
// when "DATA_NUM": "2"
{
"RESPONSE": {
"DATA_NUM": "2",
"USER_LIST": [
{
"USER_NAME": "Jason",
"USER_AGE": "30",
"ID": "12345"
},
{
"USER_NAME": "Amy",
"USER_AGE": "24",
"ID": "67890"
}
]
}
}
Model
struct UserDataResponse: Codable {
let RESPONSE: UserData?
}
struct UserData: Codable {
let DATA_NUM: String?
let USER_LIST: [UserInfo]?
}
struct UserInfo: Codable {
let USER_NAME: String?
let USER_AGE: String?
let ID: String?
}
Decode
do {
let res: UserDataResponse = try JSONDecoder().decode(UserDataResponse.self, from: data)
guard let userData: UserData = res.RESPONSE else { return }
print("Successfully decoded", userData)
} catch {
print("failed to decode") // failed to decode when "DATA_NUM" is "0" or "1"
}
Here is a solution using a custom init(from:) to handle the strange USER_LIST
struct UserDataResponse: Decodable {
let response : UserData
enum CodingKeys: String, CodingKey {
case response = "RESPONSE"
}
}
struct UserData: Decodable {
let dataNumber: String
let users: [UserInfo]
enum CodingKeys: String, CodingKey {
case dataNumber = "DATA_NUM"
case users = "USER_LIST"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
dataNumber = try container.decode(String.self, forKey: .dataNumber)
if let _ = try? container.decode(String.self, forKey: .users) {
users = []
return
}
var nestedContainer = try container.nestedUnkeyedContainer(forKey: .users)
var temp: [UserInfo] = []
do {
while !nestedContainer.isAtEnd {
let user = try nestedContainer.decode(UserInfo.self)
temp.append(user)
}
} catch {}
self.users = temp
}
}
struct UserInfo: Decodable {
let name: String
let age: String
let id: String
enum CodingKeys: String, CodingKey {
case name = "USER_NAME"
case age = "USER_AGE"
case id = "ID"
}
}
An example (data1,data2,data3 corresponds to the json examples posted in the question)
let decoder = JSONDecoder()
for data in [data1, data2, data3] {
do {
let result = try decoder.decode(UserDataResponse.self, from: data)
print("Response \(result.response.dataNumber)")
print(result.response.users)
} catch {
print(error)
}
}
Output
Response 0
[]
Response 1
[__lldb_expr_93.UserInfo(name: "Jason", age: "30", id: "12345")]
Response 2
[__lldb_expr_93.UserInfo(name: "Jason", age: "30", id: "12345"), __lldb_expr_93.UserInfo(name: "Amy", age: "24", id: "67890")]
Edit with alternative solution for the while loop
In the above code there is a while loop surrounded by a do/catch so that we exit the loop as soon an error is thrown and this works fine since the problematic empty string is the last element in the json array. This solution was chosen since the iterator for the nestedContainer is not advanced to the next element if the decoding fails so just doing the opposite with the do/catch (where the catch clause is empty) inside the loop would lead to an infinite loop.
An alternative solution that do work is to decode the "" in the catch to advance the iterator. I am not sure if this is needed here but the solution becomes a bit more flexible in case the empty string is somewhere else in the array than last.
Alternative loop:
while !nestedContainer.isAtEnd {
do {
let user = try nestedContainer.decode(UserInfo.self)
temp.append(user)
} catch {
_ = try! nestedContainer.decode(String.self)
}
}
You can write this code to resolve this array string issue.
struct UserDataResponse: Codable {
let RESPONSE: UserData?
}
struct UserData: Codable {
let DATA_NUM: String?
let USER_LIST: [UserInfo]?
struct USER_LIST: Codable {
var USER_LIST: CustomMetadataType
}
}
enum CustomMetadataType: Codable {
case array([String])
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .array(container.decode(Array.self))
} catch DecodingError.typeMismatch {
do {
self = try .string(container.decode(String.self))
} catch DecodingError.typeMismatch {
throw DecodingError.typeMismatch(CustomMetadataType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload not of an expected type"))
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .array(let array):
try container.encode(array)
case .string(let string):
try container.encode(string)
}
}
}
struct UserInfo: Codable {
let USER_NAME: String?
let USER_AGE: String?
let ID: String?
}
If an array in JSON is at root level, then code is simple and beautiful:
JSONDecoder().decode([T].self, data)
But how does it work under the hood?
I want to know this in order to implement a custom decoder (with the same calling style) in a case when the array is not at the root level.
For example:
{
"status": "success",
"data": {
"base": {
"symbol": "USD",
"sign": "$"
},
"coins": [
{
"name": "Bitcoin",
"price": 7783.1949110647,
},
{
"name": "Ethereum",
"price": 198.4835955777,
},
{
"name": "Tether",
"price": 1.0026682789,
},
{
"name": "Litecoin",
"price": 45.9617330332,
}
]
}
}
struct Coin: Decodable {
let name: String
let price: Double
init(from decoder: Decoder) throws {
let rootContainer = try decoder.container(keyedBy: CodingKeys.self)
let nestedContainer = try rootContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
var unkeyedContainer = try nestedContainer.nestedUnkeyedContainer(forKey: .coins)
let coinContainer = try unkeyedContainer.nestedContainer(keyedBy: CodingKeys.self)
name = try coinContainer.decode(String.self, forKey: .name)
price = try coinContainer.decode(Double.self, forKey: .price)
}
enum CodingKeys: String, CodingKey {
case data
case coins
case name
case price
}
}
It almost works!
When .decode(Coin.self, data) it just returns single, the very first element in the array.
When .decode([Coin].self, data) sadly, but it throws the error:
Expected to decode Array, but found a dictionary instead.
Looks like I've missed some last step to make it works in a way I want.
You could define the structures to mirror your JSON:
struct ResponseObject: Codable {
let status: String
let data: Currency
}
struct CurrencyBase: Codable {
let symbol: String
let sign: String
}
struct Currency: Codable {
let base: CurrencyBase
let coins: [Coin]
}
struct Coin: Codable {
let name: String
let price: Double
}
Then you can .decode(ResponseObject.self, from: data).
try this
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let input = """
{
"status": "success",
"data": {
"base": {
"symbol": "USD",
"sign": "$"
},
"coins": [
{
"name": "Bitcoin",
"price": 7783.1949110647,
},
{
"name": "Ethereum",
"price": 198.4835955777,
},
{
"name": "Tether",
"price": 1.0026682789,
},
{
"name": "Litecoin",
"price": 45.9617330332,
}
]
}
}
"""
let decodedData = try? JSONDecoder().decode(TotalData.self, from: input.data(using: .utf8)!)
print ("\(String(describing: decodedData))")
}
struct Coin: Decodable {
let name: String
let price: Double
}
struct Base: Decodable {
let symbol: String
let sign: String
}
struct CoinsData: Decodable {
let base: Base
let coins: [Coin]
}
struct TotalData: Decodable {
let status: String
let data: CoinsData
}
}
Make a type to get rid of the containing nonsense, and then you can keep Coin clean! π§Όπ°
struct Coin: Decodable {
let name: String
let price: Double
}
extension Coin {
struct π: Decodable {
enum CodingKey: Swift.CodingKey { case data, coins }
init(from decoder: Decoder) throws {
coins = try .init(container:
decoder.container(keyedBy: CodingKey.self)
.nestedContainer(keyedBy: CodingKey.self, forKey: .data)
.nestedUnkeyedContainer(forKey: .coins)
) { try $0.decode(Coin.self) }
}
let coins: [Coin]
}
}
try JSONDecoder().decode(Coin.π.self, from: data).coins
(π looks like Kirby but is a purse.)
public extension Array {
/// Iterate through an `UnkeyedDecodingContainer` and create an `Array`.
/// - Parameters:
/// - iterate: Mutates `container` and returns an `Element`, or `throw`s.
init(
container: UnkeyedDecodingContainer,
iterate: (inout UnkeyedDecodingContainer) throws -> Element
) throws {
try self.init(
initialState: container,
while: { !$0.isAtEnd },
iterate: iterate
)
}
}
public extension Array {
/// A hack to deal with `Sequence.next` not being allowed to `throw`.
/// - Parameters:
/// - initialState: Mutable state.
/// - continuing: Check the state to see if iteration is complete.
/// - iterate: Mutates the state and returns an `Element`, or `throw`s.
init<State>(
initialState: State,
while continuing: #escaping (State) -> Bool,
iterate: (inout State) throws -> Element
) throws {
var state = initialState
self = try
Never.ending.lazy
.prefix { continuing(state) }
.map { try iterate(&state) }
}
}
public extension Never {
/// An infinite sequence whose elements don't matter.
static var ending: AnySequence<Void> { .init { } }
}
public extension AnySequence {
/// Use when `AnySequence` is required / `AnyIterator` can't be used.
/// - Parameter getNext: Executed as the `next` method of this sequence's iterator.
init(_ getNext: #escaping () -> Element?) {
self.init( Iterator(getNext) )
}
}
Not exactly what I was trying to achieve in my initial question of this post, but is also a very satisfying code:
struct Container: Decodable, IteratorProtocol, Sequence {
private var unkeyedContainer: UnkeyedDecodingContainer
var coin: Coin?
init(from decoder: Decoder) throws {
let rootContainer = try decoder.container(keyedBy: CodingKeys.self)
let nestedContainer = try rootContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
unkeyedContainer = try nestedContainer.nestedUnkeyedContainer(forKey: .coins)
}
mutating func next() -> Coin? {
guard !unkeyedContainer.isAtEnd else { return nil }
if let coin = try? unkeyedContainer.decode(Coin.self) { return coin } else { return nil }
}
enum CodingKeys: String, CodingKey {
case data
case coins
}
}
struct Coin: Decodable {
let name: String
let price: Double
}
Usage:
let coins: [Coins]
let decoder = JSONDecoder()
coins = Array(decoder.decode(Container.self, data))
That's it. It works! Thank you everyone for hints.
Is there anyone can help me fix my model? It seems it does not match with the JSON from API Response.
JSON response from postman
{
"error_code": 0,
"data": [
{
"kode": "001",
"name": "BANK INDONESIA PUSAT JAKARTA"
},
{
"kode": "002",
"name": "PT. BANK RAKYAT INDONESIA (Persero) Tbk."
},
{
"kode": "003",
"name": "BANK EKSPOR INDONESIA"
}
],
"msg": "OK"
}
Last Model Edited:
struct ObjectBank: Codable {
let errorCode: Int
let data: [Bank]
let msg: String
enum CodingKeys : String, CodingKey {
case errorCode = "error_code" , data , msg
}
}
struct Bank: Codable {
let kode: String
let name: String
}
Still got error like this
Store model using alamofire
private static func performRequest<T:Decodable>(route:APIRouter,
decoder: JSONDecoder = JSONDecoder(), completion:#escaping
(Result<T>)->Void) -> DataRequest {
// Alamofire.request(route).responseJSON {
// response in
// print(response)
// }
return Alamofire.request(route).responseJSONDecodable (decoder:
decoder){ (response: DataResponse<T>) in
//print(response)
completion(response.result)
}
}
data is an array not dictionary
let data:[Bank]
//
struct ObjectBank: Codable {
let errorCode: Int
let data: [Bank]
let msg: String
enum CodingKeys : String, CodingKey {
case errorCode = "error_code" , data , msg
}
}
struct Bank: Codable {
let kode: String
let name: String
}
//
do {
let dic = try JSONDecoder().decode(ObjectBank.self,data)
}
catch {
print(error)
}
The structure of your response is ok in principle which you can see using the following Playground:
import Cocoa
let jsonData = """
{
"error_code": 0,
"data": [
{
"kode": "001",
"name": "BANK INDONESIA PUSAT JAKARTA"
},
{
"kode": "002",
"name": "PT. BANK RAKYAT INDONESIA (Persero) Tbk."
},
{
"kode": "003",
"name": "BANK EKSPOR INDONESIA"
}
],
"msg": "OK"
}
""".data(using: .utf8)!
struct ObjectBank: Codable {
let errorCode: Int
let data: [Bank]
let msg: String
enum CodingKeys : String, CodingKey {
case errorCode = "error_code" , data , msg
}
}
struct Bank: Codable {
let kode: String
let name: String
}
do {
let banks = try JSONDecoder().decode(ObjectBank.self, from: jsonData)
print(banks)
} catch {
print(error)
}
This will parse without error. Since I do not know AlamoFire very well I have to assume that there is something going wrong with the type of your completion closure. It will "somehow" have to guess that you want to parse ObjectBank in order to make any sense of your response.
Maybe you would have an easier time with responseData?
I have a link that returns a json file, I try to print the data but it does not work it is always nil, here is the link:
http://heroapps.co.il/employee-tests/ios/logan.json
And my code:
struct DataClass: Codable {
let name: String?
let nickname: String?
let image: URL?
let dateOfBirth: Int?
let powers: [String]?
let actorName: String?
let movies: [Movie]?
enum CodingKeys: String, CodingKey {
case name = "name"
case nickname = "nickname"
case image = "image"
case dateOfBirth = "dateOfBirth"
case powers = "powers"
case actorName = "actorName"
case movies = "movies"
}
}
struct Movie: Codable {
let name: String?
let year: Int?
enum CodingKeys: String, CodingKey {
case name = "name"
case year = "year"
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let gitUrl = URL(string: "http://heroapps.co.il/employee-tests/ios/logan.json") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(Movie.self, from: data)
print(gitData.name ?? "") //Print nil
} catch let err {
print("Err", err)
}
}.resume()
}
Thank you for helping me find where my error comes from, this is the first time I use this method to retrieve JSON data
You are not parsing the top level of the JSON. (success, errorCode, message and data).
Playground code for testing...
import Foundation
let jsonData = """
{
"success": true,
"errorCode": 0,
"message": "Succcess",
"data": {
"name": "Logan Howlett",
"nickname": "The Wolverine",
"image": "http://heroapps.co.il/employee-tests/ios/logan.jpg",
"dateOfBirth": 1880,
"powers": [
"Adamantium Bones",
"Self-Healing",
"Adamantium Claws"
],
"actorName": "Hugh Jackman",
"movies": [
{
"name": "X-Men Origins: Wolverine",
"year": 2009
},
{
"name": "The Wolverine",
"year": 2013
},
{
"name": "X-Men: Days of Future Past",
"year": 2014
},
{
"name": "Logan",
"year": 2017
}
]
}
}
""".data(using: .utf8)!
struct JSONResponse: Codable {
let success: Bool
let errorCode: Int
let message: String
let data: DataClass
}
struct DataClass: Codable {
let name: String?
let nickname: String?
let image: URL?
let dateOfBirth: Int?
let powers: [String]?
let actorName: String?
let movies: [Movie]?
enum CodingKeys: String, CodingKey {
case name = "name"
case nickname = "nickname"
case image = "image"
case dateOfBirth = "dateOfBirth"
case powers = "powers"
case actorName = "actorName"
case movies = "movies"
}
}
struct Movie: Codable {
let name: String?
let year: Int?
enum CodingKeys: String, CodingKey {
case name = "name"
case year = "year"
}
}
do {
let result = try JSONDecoder().decode(JSONResponse.self, from: jsonData)
print(result)
} catch {
print(error)
}
How does the Swift 4 Decodable protocol cope with a dictionary containing a key whose name is not known until runtime? For example:
[
{
"categoryName": "Trending",
"Trending": [
{
"category": "Trending",
"trailerPrice": "",
"isFavourit": null,
"isWatchlist": null
}
]
},
{
"categoryName": "Comedy",
"Comedy": [
{
"category": "Comedy",
"trailerPrice": "",
"isFavourit": null,
"isWatchlist": null
}
]
}
]
Here we have an array of dictionaries; the first has keys categoryName and Trending, while the second has keys categoryName and Comedy. The value of the categoryName key tells me the name of the second key. How do I express that using Decodable?
The key is in how you define the CodingKeys property. While it's most commonly an enum it can be anything that conforms to the CodingKey protocol. And to make dynamic keys, you can call a static function:
struct Category: Decodable {
struct Detail: Decodable {
var category: String
var trailerPrice: String
var isFavorite: Bool?
var isWatchlist: Bool?
}
var name: String
var detail: Detail
private struct CodingKeys: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
init?(stringValue: String) { self.stringValue = stringValue }
static let name = CodingKeys.make(key: "categoryName")
static func make(key: String) -> CodingKeys {
return CodingKeys(stringValue: key)!
}
}
init(from coder: Decoder) throws {
let container = try coder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.detail = try container.decode([Detail].self, forKey: .make(key: name)).first!
}
}
Usage:
let jsonData = """
[
{
"categoryName": "Trending",
"Trending": [
{
"category": "Trending",
"trailerPrice": "",
"isFavourite": null,
"isWatchlist": null
}
]
},
{
"categoryName": "Comedy",
"Comedy": [
{
"category": "Comedy",
"trailerPrice": "",
"isFavourite": null,
"isWatchlist": null
}
]
}
]
""".data(using: .utf8)!
let categories = try! JSONDecoder().decode([Category].self, from: jsonData)
(I changed isFavourit in the JSON to isFavourite since I thought it was a mispelling. It's easy enough to adapt the code if that's not the case)
You can write a custom struct that functions as a CodingKeys object, and initialize it with a string such that it extracts the key you specified:
private struct CK : CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
Thus, once you know what the desired key is, you can say (in the init(from:) override:
let key = // whatever the key name turns out to be
let con2 = try! decoder.container(keyedBy: CK.self)
self.unknown = try! con2.decode([Inner].self, forKey: CK(stringValue:key)!)
So what I ended up doing is making two containers from the decoder β one using the standard CodingKeys enum to extract the value of the "categoryName" key, and another using the CK struct to extract the value of the key whose name we just learned:
init(from decoder: Decoder) throws {
let con = try! decoder.container(keyedBy: CodingKeys.self)
self.categoryName = try! con.decode(String.self, forKey:.categoryName)
let key = self.categoryName
let con2 = try! decoder.container(keyedBy: CK.self)
self.unknown = try! con2.decode([Inner].self, forKey: CK(stringValue:key)!)
}
Here, then, is my entire Decodable struct:
struct ResponseData : Codable {
let categoryName : String
let unknown : [Inner]
struct Inner : Codable {
let category : String
let trailerPrice : String
let isFavourit : String?
let isWatchList : String?
}
private enum CodingKeys : String, CodingKey {
case categoryName
}
private struct CK : CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
init(from decoder: Decoder) throws {
let con = try! decoder.container(keyedBy: CodingKeys.self)
self.categoryName = try! con.decode(String.self, forKey:.categoryName)
let key = self.categoryName
let con2 = try! decoder.container(keyedBy: CK.self)
self.unknown = try! con2.decode([Inner].self, forKey: CK(stringValue:key)!)
}
}
And here's the test bed:
let json = """
[
{
"categoryName": "Trending",
"Trending": [
{
"category": "Trending",
"trailerPrice": "",
"isFavourit": null,
"isWatchlist": null
}
]
},
{
"categoryName": "Comedy",
"Comedy": [
{
"category": "Comedy",
"trailerPrice": "",
"isFavourit": null,
"isWatchlist": null
}
]
}
]
"""
let myjson = try! JSONDecoder().decode(
[ResponseData].self,
from: json.data(using: .utf8)!)
print(myjson)
And here's the output of the print statement, proving that we've populated our structs correctly:
[JustPlaying.ResponseData(
categoryName: "Trending",
unknown: [JustPlaying.ResponseData.Inner(
category: "Trending",
trailerPrice: "",
isFavourit: nil,
isWatchList: nil)]),
JustPlaying.ResponseData(
categoryName: "Comedy",
unknown: [JustPlaying.ResponseData.Inner(
category: "Comedy",
trailerPrice: "",
isFavourit: nil,
isWatchList: nil)])
]
Of course in real life we'd have some error-handling, no doubt!
EDIT Later I realized (in part thanks to CodeDifferent's answer) that I didn't need two containers; I can eliminate the CodingKeys enum, and my CK struct can do all the work! It is a general purpose key-maker:
init(from decoder: Decoder) throws {
let con = try! decoder.container(keyedBy: CK.self)
self.categoryName = try! con.decode(String.self, forKey:CK(stringValue:"categoryName")!)
let key = self.categoryName
self.unknown = try! con.decode([Inner].self, forKey: CK(stringValue:key)!)
}
Here's what I eventually came up for this json:
let json = """
{
"BTC_BCN":{
"last":"0.00000057",
"percentChange":"0.03636363",
"baseVolume":"47.08463318"
},
"BTC_BELA":{
"last":"0.00001281",
"percentChange":"0.07376362",
"baseVolume":"5.46595029"
}
}
""".data(using: .utf8)!
We make such a structure:
struct Pair {
let name: String
let details: Details
struct Details: Codable {
let last, percentChange, baseVolume: String
}
}
then decode:
if let pairsDictionary = try? JSONDecoder().decode([String: Pair.Details].self, from: json) {
var pairs: [Pair] = []
for (name, details) in pairsDictionary {
let pair = Pair(name: name, details: details)
pairs.append(pair)
}
print(pairs)
}
It is also possible to call not pair.details.baseVolume, but pair.baseVolume:
struct Pair {
......
var baseVolume: String { return details.baseVolume }
......
Or write custom init:
struct Pair {
.....
let baseVolume: String
init(name: String, details: Details) {
self.baseVolume = details.baseVolume
......