parsing two different object's array from JSON response - ios

I'm trying to parse JSON data .. i know how to do it for one object array .. but i don't know how to do it for a response which has to two arrays of different objects ..
for example this is the JSON:
{
"shifts": [
{
"id": 4,
"region": "Eastren",
"city": "Khobar",
"nationality": "1",
"id_service": 2,
"shift_date": "2018-04-05",
"shift_type": "night",
"weekday": "sunday",
"quantity_staff": 8,
"lead_hours": 2,
"created_at": "2018-04-23 11:46:20",
"updated_at": "2018-04-24 08:46:14",
"deleted_at": null
},
{
"id": 5,
"region": "Eastren",
"city": "Khobar",
"nationality": "Phili",
"id_service": 2,
"shift_date": "2018-04-04",
"shift_type": "night",
"weekday": "sunday",
"quantity_staff": 8,
"lead_hours": 2,
"created_at": "2018-04-23 11:47:25",
"updated_at": "2018-04-23 12:53:05",
"deleted_at": "2018-04-23"
}
],
"prices": [
{
"id": 1,
"id_service": 2,
"nationality": "Phili",
"price": 150,
"created_at": "2018-04-23 11:43:40",
"updated_at": "2018-04-23 11:43:40",
"deleted_at": null
}
]
}
it has two array of objects .. shifts and prices .. how to parse each one of them?
my function:
func GetShiftsAndPrices(id: Int){
let todosEndpoint: String = "my link"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "POST"
todosUrlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let newTodo: [String: Any] = ["id_service": id]
let jsonTodo: Data
do {
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
todosUrlRequest.httpBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo")
return
}
let session = URLSession.shared
let task = session.dataTask(with: todosUrlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /public/api/login_customer")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
//WHAT SHOULD I DO HERE?
print("Success!")
} catch {
print("error parsing response from POST")
return
}
}
task.resume()}
}
I have classes for both shift and price .. and know how to get each one if it was alone in a response .. like:
shifts:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let shifts1 = try decoder.decode([Shifts].self, from: responseData)
var shifts = [Shift]()
for shift in shifts1{
let newshift = Shift(id: shift.id, region: shift.region, city: shift.city, nationality: shift.nationality, idService: shift.idService, shiftDate: shift.shiftDate, shiftType: shift.shiftType, weekday: shift.weekday, quantityStaff: shift.quantityStaff, leadHours: shift.leadHours)
shifts.append(newshift)
}
let userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: shifts)
userDefaults.set(encodedData, forKey: "shifts")
userDefaults.synchronize()
let decoded = userDefaults.object(forKey: "shifts") as! Data
let decodedShift = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Shift]
for shift in decodedShift {
print(shift.id)
}
prices:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let prices1 = try decoder.decode([Prices].self, from: responseData)
print("1")
var prices = [Price]()
for price in prices1{
let newprice = Price(id: price.id, idService: price.idService,nationality: price.nationality, price: price.price)
print("2")
prices.append(newprice)
print(newprice.nationality)
}
let userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: prices)
userDefaults.set(encodedData, forKey: "prices")
userDefaults.synchronize()
let decoded = userDefaults.object(forKey: "prices") as! Data
let decodedPrice = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Price]
for price in decodedPrice {
print(price.nationality)
}
how to parse them both in one JSON response.. I'm new to this.. can someone please tell me how to do it?

Use an umbrella struct
struct Root : Decodable {
let shifts : [Shift]
let prices : [Price]
}
and two different structs for shifts and prices:
struct Shift : Decodable {
let id: Int
let region, city, nationality : String
let idService : Int
let shiftDate, shiftType, weekday : String
let quantityStaff, leadHours : Int
let createdAt, updatedAt : String
let deletedAt : String?
}
struct Price : Decodable {
let id, idService : Int
let nationality : String
let price : Int
let createdAt, updatedAt : String
let deletedAt : String?
}
To decode the JSON write
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder .decode(Root.self, from: responseData)
print(result.prices)
print(result.shifts)
} catch { print(error) }
Further I recommend to decode keys like shiftType and weekday directly into an enum for example
enum ShiftType : String, Decodable {
case day, night
}
struct Shift : Decodable {
let id: Int
...
let shiftType : ShiftType
...

let shifts = responseJson.valueFor(key:"shifts") as? [String] ?? []
let prices = responseJson.valueFor(key:"prices") as? [String] ?? []
print("\(shifts) and \(prices)")

Related

Error trying to parse JSON using URLSession in swift

I'm trying to parse a test JSON from a http adress, but I get an error saying that
"No value associated with key CodingKeys(stringValue: \"name\", intValue: nil)
The JSON looks like this. It has been validated, so it should work ok:
{
"work": [
{
"name": "Jocke",
"job": "Developer",
"date": "1985-12-30T00:00:00+0000",
"best_book": {
"id": 33245,
"title": "DiscWorld",
"author": {
"id": 345,
"name": "Terry Prattchet"
}
}
},
{
"name": "Bob",
"job": "Construction worker",
"date": "2010-01-30T00:00:00+0000",
"best_book": {
"id": 375802,
"title": "Ender's Game (Ender's Saga, #1)",
"author": {
"id": 589,
"name": "Orson Scott Card"
}
}
}
]
}
The code looks like this:
struct People: Codable {
let name: String
let job: String
enum OuterKey: String, CodingKey {
case work = "work"
}
enum codingKeys: String, CodingKey {
case name = "name"
case job = "job"
}
init(decoder: Decoder) throws {
let outerContainer = try decoder.container(keyedBy: OuterKey.self)
let innerContainer = try outerContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .work)
self.name = try innerContainer.decode(String.self, forKey: .name)
self.job = try innerContainer.decode(String.self, forKey: .job)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://api.myjson.com/bins/fe2eo") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let decodedJson = try! jsonDecoder.decode([People].self, from: data)
}
}.resume()
}
}
I'm just trying to grasp the first two keys as of now, just to see if it works. But it doesn't even get past name.
Your api returns
[{"firstName":"Jocke","job":"developer"},{"firstName":"Anna","job":"construction"},{"firstName":"Peter","job":"pilot"}]
do {
let jsonDecoder = JSONDecoder()
let decodedJson = try jsonDecoder.decode([People].self, from: data)
}
catch {
print(error)
}
struct People: Codable {
let firstName, job: String
}
just try this
struct Work:Codeable {
let work:[People]
}
struct People: Codable {
let name: String
let job: String
}
do {
let jsonDecoder = JSONDecoder()
let decodedJson = try jsonDecoder.decode(Work.self, from: data)
}
catch {
print(error)
}
if you have same name as json keys you don't need to use codingkeys

JSON data couldn’t be read

I am trying to replicate following GET request in my project:
curl -XGET 'https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt'
Here is my final code:
if let url = URL(string: "https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt"){
let urlRequest = URLRequest(url: url)
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if error == nil{
do{
if let dataReceived = data, let jsonData = try JSONSerialization.jsonObject(with: dataReceived, options: .mutableLeaves) as? [String : Any]{
print(jsonData)
}
} catch let error{
print(error.localizedDescription)
}
}
}.resume()
}
I am getting following error:
The data couldn’t be read because it isn’t in the correct format.
I tried other Stackoverflow and Reddit solution but nothing seems to be working.
API call is returning data keys in wrong format. You are receiving the keys starting from '$' or '~' e.g. '$og_title', '~stage'. That's why it's showing you an error.
You can use Codable to parse the API. For that first, you need to
make a Model struct for your API Call.
Change the variable names according to Swift Syntax. I've replaced
'$' with 'l' and '~' with 'i'. You can customize the code
according to your needs.
This is your API Call
let url = URL(string: "https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
guard ((data) != nil), let _: URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
print(dataString)
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
let model = try decoder.decode(ResponseData.self, from: data!) //Decode JSON Response Data
// Access your json data from Swift Structs e.g. model.type
print(model.data?.iurl)
} catch let parsingError {
print("Error", parsingError)
}
}
})
task.resume()
This is your Model Struct
struct ResponseData : Codable {
let data : MyData?
let type : Int?
let tags : [String]?
let campaign : String?
let feature : String?
let channel : String?
let stage : String?
enum CodingKeys: String, CodingKey {
case data = "data"
case type = "type"
case tags = "tags"
case campaign = "campaign"
case feature = "feature"
case channel = "channel"
case stage = "stage"
}
}
struct MyData : Codable {
let custom_array : [Int]?
let log_title : String?
let custom_boolean : Bool?
let custom_integer : Int?
let icreation_source : Int?
let log_description : String?
let log_image_url : String?
let istage : String?
let custom_string : String?
let ifeature : String?
let url : String?
let custom_object : Custom_object?
let iurl : String?
let ldesktop_url : String?
let itags : [String]?
let lcanonical_identifier : String?
let lone_time_use : Bool?
let iid : String?
let icampaign : String?
let ichannel : String?
enum CodingKeys: String, CodingKey {
case custom_array = "custom_array"
case log_title = "$og_title"
case custom_boolean = "custom_boolean"
case custom_integer = "custom_integer"
case icreation_source = "~creation_source"
case log_description = "$og_description"
case log_image_url = "$og_image_url"
case istage = "~stage"
case custom_string = "custom_string"
case ifeature = "~feature"
case url = "url"
case custom_object = "custom_object"
case iurl = "+url"
case ldesktop_url = "$desktop_url"
case itags = "~tags"
case lcanonical_identifier = "$canonical_identifier"
case lone_time_use = "$one_time_use"
case iid = "~id"
case icampaign = "~campaign"
case ichannel = "~channel"
}
}
struct Custom_object : Codable {
let random : String?
enum CodingKeys: String, CodingKey {
case random = "random"
}
}
The decoding code is correct.
The link is wrong, it should be https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt and not https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt
Only decoding:
import UIKit
var json = """
{
"data": {
"custom_array": [
1,
2,
3,
4,
5,
6
],
"$og_title": "Title from Deep Link",
"custom_boolean": true,
"custom_integer": 1243,
"~creation_source": 0,
"$og_description": "Description from Deep Link",
"$og_image_url": "http://www.lorempixel.com/400/400/",
"~stage": "new user",
"custom_string": "everything",
"~feature": "onboarding",
"url": "https://example.app.link/WgiqvsepqF",
"custom_object": {
"random": "dictionary"
},
"+url": "https://example.app.link/WgiqvsepqF",
"$desktop_url": "http://www.example.com",
"~tags": [
"one",
"two",
"three"
],
"$canonical_identifier": "content/123",
"$one_time_use": false,
"~id": "423196192848102356",
"~campaign": "new product",
"~channel": "facebook"
},
"type": 0,
"tags": [
"one",
"two",
"three"
],
"campaign": "new product",
"feature": "onboarding",
"channel": "facebook",
"stage": "new user"
}
"""
let data = json.data(using: .utf8)!
do {
if let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String : Any] {
print(jsonData)
}
} catch let error {
print(error)
}

Parsing json data using Codable

I am new to using Codable for parsing data from JSON and I am having trouble with the format of my JSON. I am not able to parse the correct fields into my Employee object. This is my first time using codable and dealing with a complex URL. This is how my JSON url is structured: https://ibb.co/WgDNMNT
{
"students": [
{
"uuid": "0djkdjjf734783749c",
"full_name": "Joe Morris",
"phone_number": "44445399",
"email_address": "jm99#jfgj.com",
"biography": "student of arts"
},
{
"uuid": "0djkdjjf734783749c",
"full_name": "Joe Morris",
"phone_number": "44445399",
"email_address": "jm99#jfgj.com",
"biography": "student of arts"
}
]
}
Here is my code:
struct Students: Codable {
var uuid: String?
var fullName: String?
var phoneNumber: String?
var emailAddress: String?
var biography: String?
}
//Custom Keys
enum CodingKeys: String, CodingKey{
case uuid
case fullname = "full_name"
case phoneNumber = "phone_number"
case emailAddress = "email_address"
case biography = "biography"
}
func parseData(){
guard let url = URL(string: "xxxxxxxxxx") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Error")
return }
do{
let decoder = JSONDecoder()
let model = try decoder.decode([Students].self, from: dataResponse)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
Replace
let model = try decoder.decode([Students].self, from: dataResponse)
With
let model = try decoder.decode([String:[Students]].self, from: dataResponse)
print(model["students"])

core data with duplicate entity values in swift

I am parsing some data from Json and saved into the coredata,after fetching core data showing into the tableview working fine, tableview is show all the value in repeatedly how can avoid the repeated values I tried many ways but not find way
Json format
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c202",
"name": "Leonardo Dicaprio",
"email": "leonardo_dicaprio#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
when I fetching "name" showing repeated values
these are save and fetch code
func getfetchdata()
{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Contacts")
do{
let fetchResults = try self.context.fetch(fetchRequest) as? [Contacts]
if fetchResults!.count > 0 {
for bEntity in fetchResults! {
let employeeEntity = bEntity
print(employeeEntity.name as Any)
TableviewData.append(ContactsDataVal.init(name: employeeEntity.name!,
id: employeeEntity.id!, email: employeeEntity.email!, gender: employeeEntity.gender!, address: employeeEntity.address!))
}
print("data values already")
}}
catch let error as NSError
{
print(error)
}
}
func getdata()
{
let url = URL(string: "https://api.androidhive.info/contacts/")
URLSession.shared.dataTask(with: url!) { (Data, response, error) in
do
{
let data = try JSONSerialization.jsonObject(with: Data!, options: JSONSerialization.ReadingOptions.allowFragments)as! [String:AnyObject]
let arraydata = data["contacts"]as! [[String:Any]]
for arravalues in arraydata
{
let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts", in:self.context)
let favouriteObj = Contacts(entity: entityDescription!, insertInto: self.context)
favouriteObj.name = arravalues["name"] as? String
favouriteObj.id = arravalues["id"] as? String
favouriteObj.email = arravalues["email"] as? String
favouriteObj.gender = arravalues["gender"] as? String
favouriteObj.address = arravalues["address"] as? String
do {
try self.context.save()
}
}
}catch let error as NSError{
print("error",error)
}
}
.resume()
}
how to avoid repeated values in core data and show proper data into the tableview
First of all in getdata do not save the context in each iteration of the loop, save it once after the loop.
To avoid duplicates fetch all contacts from Core Data, map them to the names and check if the array contains the received name
func getdata()
{
let url = URL(string: "https://api.androidhive.info/contacts/")
let names : [String]
do {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Contacts")
let fetchResults = try self.context.fetch(fetchRequest)
names = fetchResults.map{ $0.name }
} catch {
names = []
}
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil { print(error!); return }
do {
let data = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
let arraydata = data["contacts"] as! [[String:Any]]
for arravalues in arraydata
{
guard let name = arravalues["name"] as? String, !names.contains(name) else { continue }
let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts", in:self.context)
let favouriteObj = Contacts(entity: entityDescription!, insertInto: self.context)
favouriteObj.name = name
favouriteObj.id = arravalues["id"] as? String
favouriteObj.email = arravalues["email"] as? String
favouriteObj.gender = arravalues["gender"] as? String
favouriteObj.address = arravalues["address"] as? String
}
try self.context.save()
} catch {
print("error",error)
}
}
.resume()
}
Notes:
A Core Data fetch with generic fetch request returns always a non-optional array of the NSManagedObject subclass which is specified as generic type on success.
Never check for empty array with foo.count > 0, use !foo.isEmpty
A JSON dictionary in Swift 3+ is always [String:Any] rather than [String:AnyObject]
Handle a potential error in the dataTask completion block.
Name the first parameter in the completion block lowercased (data) to avoid a confusion with the type Data.
Omit the options parameter in jsonObject(with as the result is clearly a collection type.
Maybe there is something that can be done to the fetch request similar to How to get distinct results from a single field in Core Data (Swift 4) but another option would be to remove the duplicates by simply creating a set from the fetch result:
let fetchSet = Set(fetchResults)
and iterate over the set instead

How to parse Array of JSON to array in Swift

I'm trying to parse JSON which is like below
[
{
"People": [
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
]
},
{
"People": [
"Rose",
"John"
]
},
{
"People": [
"Ted"
]
}
]
to an array which results in:
[ ["Jack", "Jones", "Rock", "Taylor", "Rob"] , ["Rose", "John"], ["Ted"] ]
which is array of arrays.
I tried with code below
if let path = Bundle.main.path(forResource: "People", ofType: "json") {
let peoplesArray = try! JSONSerialization.jsonObject(
with: Data(contentsOf: URL(fileURLWithPath: path)),
options: JSONSerialization.ReadingOptions()
) as? [AnyObject]
for people in peoplesArray! {
print(people)
}
}
when I print "people" I get o/p as
{
People = (
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
);
}
{
People = (
"Rose",
"John"
);
}
...
I'm confused how to parse when it has "People" repeated 3 times
Trying to display content in UITableView where my 1st cell has "Jack" .."Rob" and Second cell has "Rose" , "John" and third cell as "Ted"
PLease help me to understand how to achieve this
You can do this in an elegant and type safe way leveraging Swift 4 Decodable
First define a type for your people array.
struct People {
let names: [String]
}
Then make it Decodable, so that it can be initialised with a JSON.
extension People: Decodable {
private enum Key: String, CodingKey {
case names = "People"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
self.names = try container.decode([String].self, forKey: .names)
}
}
Now you can easily decode your JSON input
guard
let url = Bundle.main.url(forResource: "People", withExtension: "json"),
let data = try? Data(contentsOf: url)
else { /* Insert error handling here */ }
do {
let people = try JSONDecoder().decode([People].self, from: data)
} catch {
// I find it handy to keep track of why the decoding has failed. E.g.:
print(error)
// Insert error handling here
}
Finally to get get your linear array of names you can do
let names = people.flatMap { $0.names }
// => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]
var peoplesArray:[Any] = [
[
"People": [
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
]
],
[
"People": [
"Rose",
"John"
]
],
[
"People": [
"Ted"
]
]
]
var finalArray:[Any] = []
for peopleDict in peoplesArray {
if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
finalArray.append(peopleArray)
}
}
print(finalArray)
output:
[["Jack", "Jones", "Rock", "Taylor", "Rob"], ["Rose", "John"], ["Ted"]]
In your case, it will be:
if let path = Bundle.main.path(forResource: "People", ofType: "json") {
let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [Any]
var finalArray:[Any] = []
for peopleDict in peoplesArray {
if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
finalArray.append(peopleArray)
}
}
print(finalArray)
}
let assume that the json is the encoded data
var arrayOfData : [String] = []
dispatch_async(dispatch_get_main_queue(),{
for data in json as! [Dictionary<String,AnyObject>]
{
let data1 = data["People"]
arrayOfData.append(data1!)
}
})
You can now use the arrayOfData. :D
what you have here is first an array of 3 objects. each object is a dictionary where the key is people and the value is an array of strings. when you're trying to do jsonserialization, you have to cast it down to the expected result. So you have first an array of objects, then you have a dictionary with String: Any, then you obtain an array of String
let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as? [AnyObject]
guard let peoplesObject = peoplesArray["people"] as? [[String:Any]] else { return }
for people in peoplesObject {
print("\(people)")
}
I couldn't pasted it in a comment, it is too long or something
static func photosFromJSONObject(data: Data) -> photosResult {
do {
let jsonObject: Any =
try JSONSerialization.jsonObject(with: data, options: [])
print(jsonObject)
guard let
jsonDictionary = jsonObject as? [NSObject: Any] as NSDictionary?,
let trackObject = jsonDictionary["track"] as? [String: Any],
let album = trackObject["album"] as? [String: Any],
let photosArray = album["image"] as? [[String: Any]]
else {
return .failure(lastFMError.invalidJSONData)
}
}
}
And the json was something like:
{
artist: {
name: Cher,
track: {
title: WhateverTitle,
album: {
title: AlbumWhatever,
image: {
small: "image.px",
medium: "image.2px",
large: "image.3px"}
....

Resources