How to parse a dictionaray and array JSON in Swift 5 - json

I'm trying to parse a JSON file with the following format:
{
"OnDemand" : {
"program" : [
{
"Sunday" : "https://example1.m4a",
"SundaySharePage" : "https://example1",
"name" : "Example 1",
"weekdays" : "Sunday"
},
{
"Monday" : "https://example2.m4a",
"MondaySharePage" : "https://example2",
"name" : "Example 2",
"weekdays" : "Monday"
}
]
}
Using this code:
struct AllPrograms: Codable {
let OnDemand: [Dictionary<String,String>: Programs]
}
struct Programs: Codable {
let program:Array<String>
}
func parsePrograms (urlString:String) {
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
let jsonDecoder = JSONDecoder()
do {
let parsedJSON = try jsonDecoder.decode(AllPrograms.self, from: data)
print(parsedJSON.OnDemand)
} catch {
print(error)
}
}
}.resume()
}
}
But I'm getting this error:
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "OnDemand", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
How do I fix this? Thank you!

use this code block to create your Model,
import Foundation
// MARK: - AllPrograms
struct AllPrograms: Codable {
let onDemand: OnDemand
enum CodingKeys: String, CodingKey {
case onDemand = "OnDemand"
}
}
// MARK: - OnDemand
struct OnDemand: Codable {
let program: [Program]
}
// MARK: - Program
struct Program: Codable {
let sunday, sundaySharePage: String?
let name, weekdays: String
let monday, mondaySharePage: String?
enum CodingKeys: String, CodingKey {
case sunday = "Sunday"
case sundaySharePage = "SundaySharePage"
case name, weekdays
case monday = "Monday"
case mondaySharePage = "MondaySharePage"
}
}
You can use this website for easly creating models according to json data.
By the way in your json there is one } missing. check your json if you use hard coded.

Related

Unable to GET from JSON API

I have tried following a variety of tutorials, and I am unable to progress on getting data from this API. I did manage to succeed on a simpler JSON ], but this one is eating up my time.
First, the JSON:
{
"object": {
"array": [
{
"id": 48,
"name": "Job No.# 48",
"description": "blah",
"start_at": "2021-03-05T13:15:00.000+11:00",
"end_at": "2021-03-05T14:15:00.000+11:00",
"map_address": "blah road"
},
{
"id": 56,
"name": "Job No.# 56",
"description": "Do it",
"start_at": "2021-06-22T11:30:00.000+10:00",
"end_at": "2021-06-22T13:30:00.000+10:00",
"map_address": " blah"
}
],
"person": {
"id": 52,
"first_name": "Bob",
"last_name": "Newby",
"mobile": "0401111111",
"email": "bob#mail.com"
}
}
}
And now my attempt at decoding it:
struct api_data: Codable {
let object : Object
}
struct Object: Codable {
let array : [array]
let person : Person
}
struct array: Codable, Identifiable {
let id : Int?
let start_at, end_at : Date?
let duration : Float?
let cancellation_type : String?
let name, description, address, city, postcode, state : String?
}
struct Person: Codable, Identifiable {
let id : Int?
let first_name, last_name, mobile, email : String?
}
class FetchShifts: ObservableObject {
#Published var shifts = [Shifts]()
init() {
let url = URL(string: "realURLhiddenForPrivacy")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("myToken", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) {(data, response, error) in
do {
if let array_data = data {
let array_data = try JSONDecoder().decode([array].self, from: array_data)
DispatchQueue.main.async {
self.array = array_data
}
} else {
print("No data")
}
} catch {
print(error)
}
}.resume()
}
}
And how I attempt to present it:
#ObservedObject var fetch = FetchArray()
var body: some View {
VStack {
List(array.shifts) { shft in
VStack(alignment: .leading) {
Text(shft.name!)
}
}
}
}
}
}
Any help is appreciated, not sure where it is I go wrong here, been at it for 5-7 hours going through tutorials.
I always recommend using app.quicktype.io to generate models from JSON if you're unfamiliar with it. Here's what it yields:
// MARK: - Welcome
struct Welcome: Codable {
let status: String
let payload: Payload
}
// MARK: - Payload
struct Payload: Codable {
let shifts: [Shift]
let worker: Worker
}
// MARK: - Shift
struct Shift: Codable, Identifiable {
let id: Int
let name, shiftDescription, startAt, endAt: String
let mapAddress: String
enum CodingKeys: String, CodingKey {
case id, name
case shiftDescription = "description"
case startAt = "start_at"
case endAt = "end_at"
case mapAddress = "map_address"
}
}
// MARK: - Worker
struct Worker: Codable {
let id: Int
let firstName, lastName, mobile, email: String
enum CodingKeys: String, CodingKey {
case id
case firstName = "first_name"
case lastName = "last_name"
case mobile, email
}
}
Then, to decode, you'd do:
do {
let decoded = try JSONDecoder().decode(Welcome.self, from: shift_data)
let shifts = decoded.payload.shifts
} catch {
print(error)
}
Note that in Swift, it's common practice to use camel case for naming, not snake case, so you'll see that CodingKeys does some conversion for that (there are automated ways of doing this as well).
Update, based on comments:
Your code would be:
if let shiftData = data {
do {
let decoded = try JSONDecoder().decode(Welcome.self, from: shiftData)
DispatchQueue.main.async {
self.shifts = decoded.payload.shifts
}
} catch {
print(error)
}
}
Instead of defining custom keys, you can automatically use
keyDecodingStrategy = .convertFromSnakeCase for your JSON decoder, and could specify custom date format or even throw a custom error in your decoder implementation.
struct Worker: Codable {
let id: Int
let firstName: String?
let lastName: String?
let mobile: String?
let email: String?
}
struct Shift: Codable, Identifiable {
let id: Int
let name: String?
let description: String?
let startAt: Date?
let endAt: Date?
let mapAddress: String?
}
struct Payload: Codable {
let shifts: [Shift]?
let worker: Worker?
}
struct Response: Codable {
let status: String
let payload: Payload?
}
class MyCustomDecoder: JSONDecoder {
override init() {
super.init()
self.keyDecodingStrategy = .convertFromSnakeCase
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
self.dateDecodingStrategy = .formatted(dateFormatter)
}
}
// Usage
if let data = json.data(using: .utf8) {
let response = try MyCustomDecoder().decode(Response.self, from: data)
print(response)
}

how to parse this complex nested Json

The Json is valid but I m getting nil with below code and struct for the returned json.
problem encountered:
at JSonDecoder.decode() : it returned this error msg:
keyNotFound(CodingKeys(stringValue: "items", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "items", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "items", intValue: nil) ("items").", underlyingError: nil))
How to get these a) image b) location from the Json
Thanks
here the code
func getJsonMapData(){
guard let mapUrl = URL(string: "https://xxxxxx/traffic-images") else { return }
URLSession.shared.dataTask(with: mapUrl) { (data, response, error) in
guard error == nil else { return}
guard let data = data else { return}
//- problem:
do {
let LocationArrDict = try JSONDecoder().decode([String:[Location]].self, from: data)else{
print(LocationArrDict)
} catch {
print(error)
}
}.resume()
}
//------------- return Json String:
{
"items":[
{
"timestamp":"2020-12-05T08:45:43+08:00",
"cameras":[
{
"timestamp":"2020-11-05T08:42:43+08:00",
"image":"https://xxxxxxxxx/traffic-images/2020/12/2ab06cd8-4dcf-434c-b758-804e690e57db.jpg",
"location":{
"latitude":1.29531332,
"longitude":103.871146
},
"camera_id":"1001",
"image_metadata":{
"height":240,
"width":320,
"md5":"c9686a013f3a2ed4af61260811661fc4"
}
},
{
"timestamp":"2020-11-05T08:42:43+08:00",
"image":"https://xxxxxxxxxx/traffic-images/2020/12/9f6d307e-8b05-414d-b27d-bf1414aa2cc7.jpg",
"location":{
"latitude":1.319541067,
"longitude":103.8785627
},
"camera_id":"1002",
"image_metadata":{
"height":240,
"width":320,
"md5":"78060d8fbdd241adf43a2f1ae5d252b1"
}
},
........
{
"timestamp":"2020-12-05T08:42:43+08:00",
"image":"https://xxxxxx/traffic-images/2020/12/98f64fe6-5985-4a8a-852f-0be24b0a6271.jpg",
"location":{
"latitude":1.41270056,
"longitude":103.80642712
},
"camera_id":"9706",
"image_metadata":{
"height":360,
"width":640,
"md5":"f63d54176620fa1d9896fa438b3cc753"
}
}
]
}
],
"api_info":{
"status":"healthy"
}
}
//------------ struct for the return Json result:
// MARK: - Location
struct Location: Codable {
let items: [Item]
let apiInfo: APIInfo
enum CodingKeys: String, CodingKey {
case items
case apiInfo = "api_info"
}
}
// MARK: - APIInfo
struct APIInfo: Codable {
let status: String
}
// MARK: - Item
struct Item: Codable {
let timestamp: Date
let cameras: [Camera]
}
// MARK: - Camera
struct Camera: Codable {
let timestamp: Date
let image: String
let location: LocationClass
let cameraID: String
let imageMetadata: ImageMetadata
enum CodingKeys: String, CodingKey {
case timestamp, image, location
case cameraID = "camera_id"
case imageMetadata = "image_metadata"
}
}
// MARK: - ImageMetadata
struct ImageMetadata: Codable {
let height, width: Int
let md5: String
}
// MARK: - LocationClass
struct LocationClass: Codable {
let latitude, longitude: Double
}
``
Error #1: The type to be decoded is wrong it must be Location.self.
Error #2: To decode the ISO date as Date you have to add the .iso8601 date decoding strategy.
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let locationArrDict = try decoder.decode(Location.self, from: data)
print(locationArrDict)
} catch {
print(error)
}
And you could decode the strings representing an URL directly to URL
You have to create your data models and describe them as the response you expect to receive. I will just give you a brief example based on your json how you would decode it.
First of all in order to decode a JSON using JSONDecoder your models have to conform to Decodable protocol. Then you have to create those models.
struct Item: Decodable {
let timestamp: Date
// let cameras: [...]
}
struct ApiInfo: Decodable {
enum Status: String, Decodable {
case healthy
}
let status: Status
}
struct Response: Decodable {
let items: [Item]
let apiInfo: ApiInfo
}
Then you have to configure your JSONDecoder and decode that JSON. As we can see clearly, your JSON uses snake_case naming convention and that is not the default one for JSONDecoder so you have to set it. Same also applies for the dates - it is used iso8601 standard of representation.
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .iso8601
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
Finally, you have you decode it.
do {
let response = try jsonDecoder.decode(Response.self, from: jsonData)
print(response)
} catch {
print(error)
}

How to properly decode nested JSON objects with Swift structs

Intent:
Receive cryptocurrency price data via Coinmarketcap API, decode it into custom structs in SWIFT and potentially store that data in a database (either CoreData or SQLite).
Context:
I am receiving the following error on JSONDecoder().decode:
Error serializing json: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "status", intValue: nil), _DictionaryCodingKey(stringValue: "credit_count", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
Questions:
How to properly interpret that error? What am I decoding wrong?
Is the data I am receiving correctly formatted? Doesn't look like
proper JSON.
The code:
import UIKit
import PlaygroundSupport
// Defining structures
struct RootObject: Decodable {
let status: [String: StatusObject?]
let data: DataObject?
}
struct StatusObject: Decodable {
let credit_count: Int?
let elapsed: Int?
let error_code: Int?
let timestamp: String?
}
struct DataObject: Decodable {
let amount: Int?
let id: Int?
let last_updated: String?
let name: String?
let quote: [QuoteObject]?
let symbol: String?
}
struct QuoteObject: Decodable {
let usd: String?
}
struct usdObject: Decodable {
let last_updated: String?
let price: String?
}
//Configuring URLSession
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["X-CMC_PRO_API_KEY": "<removed>",
"Accept": "application/json",
"Accept-Encoding": "deflate, gzip"]
let session = URLSession(configuration: config)
let url = URL(string: "https://sandbox-api.coinmarketcap.com/v1/tools/price-conversion?convert=USD&amount=1&symbol=BTC")!
//Making and handling a request
let task = session.dataTask(with: url) { data, response, error in
guard error == nil else {
print ("error: \(error!)")
return
}
guard let content = data else {
print("No data")
return
}
//Serializing and displaying the received data
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any]
else {
print("Not containing JSON")
return
}
print(json)
//Trying to decode
do {
let prices = try JSONDecoder().decode(RootObject.self, from: data!)
print(prices)
} catch let decodeError {
print("Error serializing json:", decodeError)
}
}
task.resume()
The data response and the error:
["status": {
"credit_count" = 1;
elapsed = 6;
"error_code" = 0;
"error_message" = "<null>";
timestamp = "2019-02-16T11:10:22.147Z";
}, "data": {
amount = 1;
id = 1;
"last_updated" = "2018-12-22T06:08:23.000Z";
name = Bitcoin;
quote = {
USD = {
"last_updated" = "2018-12-22T06:08:23.000Z";
price = "3881.88864625";
};
};
symbol = BTC;
}]
Error serializing json: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "status", intValue: nil), _DictionaryCodingKey(stringValue: "credit_count", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
Edit 1:
Properly serialized JSON:
{
"status": {
"timestamp": "2019-02-16T18:54:05.499Z",
"error_code": 0,
"error_message": null,
"elapsed": 6,
"credit_count": 1
},
"data": {
"id": 1,
"symbol": "BTC",
"name": "Bitcoin",
"amount": 1,
"last_updated": "2018-12-22T06:08:23.000Z",
"quote": {
"USD": {
"price": 3881.88864625,
"last_updated": "2018-12-22T06:08:23.000Z"
}
}
}
}
There are a lot of issues in the structs.
The main issue is that the value for data is a dictionary which is decoded into a struct rather than into another dictionary. Other issues are that the type of id is String and price is Double.
APIs like Coinmarketcap send reliable data so don't declare everything as optional. Remove the question marks.
The structs below are able to decode the JSON. The quotes are decoded into a dictionary because the keys change. Add the .convertFromSnakeCase key decoding strategy to get camelCased keys. The dates are decoded as Date by adding an appropriate date decoding strategy.
I removed all those redundant ...Object occurrences except DataObject because the Data struct already exists.
struct Root: Decodable {
let status: Status
let data: DataObject
}
struct Status: Decodable {
let creditCount: Int
let elapsed: Int
let errorCode: Int
let timestamp: Date
}
struct DataObject: Decodable {
let amount: Int
let id: String
let lastUpdated: Date
let name: String
let quote: [String:Quote]
let symbol: String
}
struct Quote: Decodable {
let lastUpdated: Date
let price: Double
}
//Trying to decode
do {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let result = try decoder.decode(Root.self, from: data!)
let quotes = result.data.quote
for (symbol, quote) in quotes {
print(symbol, quote.price)
}
} catch {
print(error)
}

JSON Parsing Swift 4

I was trying to parse some JSON data but had some trouble. Here is the JSON:
{
"result": {
"artist": {
"name": "The Beatles"
},
"track": {
"name": "Yesterday",
"text": "[Verse 1]\nYesterday\nAll my troubles seemed so far away\nNow it looks as though they're here to stay\nOh, I believe in yesterday\n\n[Verse 2]\nSuddenly\nI'm not half the man I used to be\nThere's a shadow hanging over me\nOh, yesterday came suddenly\n\n[Chorus]\nWhy she had to go\nI don't know, she wouldn't say\nI said something wrong\nNow I long for yesterday\n\n[Verse 3]\nYesterday\nLove was such an easy game to play\nNow I need a place to hide away\nOh, I believe in yesterday\n\n[Chorus]\nWhy she had to go\nI don't know, she wouldn't say\nI said something wrong\nNow I long for yesterday\n\n[Verse 4]\nYesterday\nLove was such an easy game to play\nNow I need a place to hide away\nOh, I believe in yesterday",
"lang": {
"code": "en",
"name": "English"
}
},
"copyright": {
"notice": "Yesterday lyrics are property and copyright of their owners. Commercial use is not allowed.",
"artist": "Copyright The Beatles",
"text": "All lyrics provided for educational purposes and personal use only."
},
"probability": "75.00",
"similarity": 1
}
}
And here is my code so far:
guard let url = URL(string: "https://orion.apiseeds.com/api/music/lyric/Beatles\Yesterday?apikey=xxx") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
}
guard let data = data else { return }
do {
let data = try JSONDecoder().decode(Result.self, from: data)
print(data)
} catch let jsonError {
print(jsonError)
}
}.resume()
struct Result: Codable {
let artist: [Artist]
}
struct Artist: Codable {
let name: String
}
The error that I get when I try to run it is:
keyNotFound(CodingKeys(stringValue: "artist", intValue: nil),
Swift.DecodingError.Context(codingPath: [], debugDescription: "No
value associated with key CodingKeys(stringValue: \"artist\",
intValue: nil) (\"artist\").", underlyingError: nil))
All I would like to do is get the lyrics from the song.
Please could someone look at this as I am struggling quite a lot.
Create a proper struct for your model if something comes with a nil, make it optional otherwise it will crash, to convert JSON to Objects you can use this online tool for the future, is quite useful! https://app.quicktype.io/
struct AudioSearch: Codable {
let result: Result
}
struct Result: Codable {
let artist: Artist
let track: Track
let copyright: Copyright
let probability: String
let similarity: Int
}
struct Artist: Codable {
let name: String
}
struct Copyright: Codable {
let notice, artist, text: String
}
struct Track: Codable {
let name, text: String
let lang: Lang
}
struct Lang: Codable {
let code, name: String
}
And use the decode like this:
let result = try JSONDecoder().decode(AudioSearch.self, from: data)
You should create struct like below for your JSON,
struct ResultResponse: Codable {
let result: Result
}
struct Result: Codable {
let artist: Artist
let track: Track
let copyright: Copyright
let probability: String
let similarity: Int
}
struct Artist: Codable {
let name : String
}
struct Track: Codable {
let lang: Language
let name: String
let text: String
}
struct Language: Codable {
let code: String
let name: String
}
struct Copyright: Codable {
let notice:String
let artist: String
let text: String
}
Parse it like below,
let result = try JSONDecoder().decode(ResultResponse.self, from: data)
Whenever you have any doubt creating JSON Codable, You can create Codable from json4swift. Paste your valid JSON String and it will create Codable objects for you.
app.quicktype.io is nice solution to create Codable for your JSON.

URLSession Type Mismatch Error

I'm getting an Type Mismatch error when trying to parse json with Swift jSon Decoder.
I just can't find a way to parse it normally.
The Error:
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath:
[CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "itemArr", intValue: nil),
CodingKeys(stringValue: "price", intValue: nil)], debugDescription:
"Expected to decode String but found a number instead.",
underlyingError:
nil))
The Decoder Code:
func getDealDetails(id : String ,completion : #escaping ()->())
{
let jsonUrl = "https://androidtest.inmanage.com/api/1.0/android/getDeal_\(id).txt"
guard let url = URL(string: jsonUrl) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do
{
let deal = try JSONDecoder().decode(ResultDetails.self, from: data)
AppManager.shared.dealToShow = deal.data.itemArr
}catch
{
print("There's an error: \(error)")
}
completion()
}.resume()
}
}
And The Classes:
First:
class ResultDetails : Decodable
{
let data : DataDetails
init(data : DataDetails) {
self.data = data
}
}
Second:
class DataDetails : Decodable
{
let itemArr: ItemArr
init(itemArr: ItemArr) {
self.itemArr = itemArr
}
}
And Third:
class ItemArr : Decodable
{
let id, title, price, description: String
let image: String
let optionsToShow: Int
let gps: Gps
let website, phone: String
init(id: String, title: String, price: String, description: String, image: String, optionsToShow: Int, gps: Gps, website: String, phone: String) {
self.id = id
self.title = title
self.price = price
self.description = description
self.image = image
self.optionsToShow = optionsToShow
self.gps = gps
self.website = website
self.phone = phone
}
I think I tried everything for the last 6 hours to fix it, please help!
EDIT:
I put a wrong third class. now it's the right one
The error message is wrong. According to the JSON link and your classes it's supposed to be
CodingKeys(stringValue: "price", intValue: nil)], debugDescription:
Expected to decode Int but found a string/data instead.,
However it's going to tell you exactly what's wrong: The value for key price is a String rather than an Int.
You have to read the JSON carefully. The format is very simple. For example everything in double quotes is String, there is no exception.
Your data structure is too complicated. Use structs and drop the initializers. By the way there is a typo ItemsArr vs. ItemArr and there is no key orderNum.
The key image can be decoded as URL. This is sufficient
struct ResultDetails : Decodable {
let data : DataDetails
}
struct DataDetails : Decodable {
let itemArr: ItemArr
}
struct ItemArr : Decodable {
let id, title: String
let price: String
let image: URL
// let orderNum: Int
}
Specify the CodingKeys only if you want to map the keys. In your case you can even omit the CodingKeys, use theconvertFromSnakeCase strategy instead.
decoder.keyDecodingStrategy = .convertFromSnakeCase
Yes you have an error
let price: Int should be let price: String because it string in Json "price": "896" -- > String
Example for Int "optionsToShow":1 --> this is Int
Here is complete code you can use
import Foundation
struct ResultDetails: Codable {
let data: DataDetails
}
struct DataDetails: Codable {
let itemArr: ItemArr
}
struct ItemArr: Codable {
let id, title, price, description: String
let image: String
let optionsToShow: Int
let gps: Gps
let website, phone: String
}
struct Gps: Codable {
let lat, lon: String
}
// MARK: Convenience initializers
extension ResultDetails {
init(data: Data) throws {
self = try JSONDecoder().decode(ResultDetails.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}