JSON Data Type Mismatch in Swift

I followed the structure correctly, but it keeps throwing an error.

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

Data Model:

struct DataModel : Codable {
    let success : Bool
    let result : [CountryData]
    
}

struct CountryData : Codable {
    let country : String
    let totalCases : String
    let newCases : String
    let totalDeaths : String
    let newDeaths : String
    let totalRecovered : String
    let activeCases : String
}

Sample JSON data:

{
  "success": true,
  "result": [
    {
      "country": "China",
      "totalcases": "80,881",
      "newCases": "+21",
      "totaldeaths": "3,226",
      "newDeaths": "+13",
      "totalRecovered": "68,709",
      "activeCases": "8,946"
    },
    {
      "country": "Italy",
      "totalcases": "27,980",
      "newCases": "",
      "totaldeaths": "2,158",
      "newDeaths": "",
      "totalRecovered": "2,749",
      "activeCases": "23,073"
    },
    "..."
  ]
}

Decoding Logic:

let decoder = JSONDecoder()
        do {
            let countries = try decoder.decode([CountryData].self, from: jsonData)
          for i in 0..<countries.count {
            print (countries[i].country)
          }
        } catch {
          print(error)
        }

Answer №1

To begin, make changes to the result structure by defining custom CodingKeys (keep in mind the difference between totalCases in the model and totalcases in the JSON):

struct result: Codable {
    enum CodingKeys: String, CodingKey {
        case country, newCases, newDeaths, totalRecovered, activeCases
        case totalCases = "totalcases"
        case totalDeaths = "totaldeaths"
    }
    
    let country: String
    let totalCases: String
    let newCases: String
    let totalDeaths: String
    let newDeaths: String
    let totalRecovered: String
    let activeCases: String
}

Next, when decoding the data, use veriler.self instead of [result].self:

let decoder = JSONDecoder()
do {
    let result = try decoder.decode(veriler.self, from: data!)
    let countries = result.result
    for i in 0 ..< countries.count {
        print(countries[i].country)
    }
} catch {
    print(error)
}

Remember to adhere to Swift conventions and name your structs as Result or Veriler (with instances being lowercase).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JSON into a multidimensional array in PHP and then querying it into an SQL database

I'm currently facing a challenge with transferring data from a multidimensional JSON array to SQL. Here is the content of my JSON file (data.json): { "Data 1": { "Text1": "Anything1", "Text2": "Anything2" }, "Data 2": { ...

Building custom components in Vue.js/NuxtJS can be a breeze when using a default design that can be easily customized through a JSON configuration

Currently, I am in the process of developing a NuxtJS website where the pages and components can either have a generic design by default or be customizable based on client specifications provided in the URL. The URL structure is as follows: http://localh ...

Utilizing Flask templates to embed JSON data

I am looking to format JSON data in my app using json.dumps() for a more visually appealing display. Currently, my template structure is as follows: <table> {% for test in list_of_decoded_json %} <tr> <td><pre>{{ test|s ...

Attempting to access the nested JSONObject within another JSONObject

I have this JSON I generated: { "error":false, "0":{ "tvInfo":{ "id":"0", "name":"The War of Thrones", "type_id":"1", "score":"8.1", "votes":"780", "created_date":"2011-04-17", ...

Dynamically insert a JSON object at a nested level within a dictionary

Currently, I'm in the middle of developing a script that will auto-generate test data based on a json spec. The main goal of this script is to build a json object or Python dictionary called record To streamline the process, I've opted to utiliz ...

Using triple nested for loops in Python to iterate through a JSON object

I am trying to extract the latitude and longitude data from a Python object. Here is a snippet of the object: { "Siri": { "ServiceDelivery": { "ResponseTimestamp": "2014-08-09T15:32:13.078-04:00", "VehicleMonitoringDelivery": [ { "VehicleAct ...

Storing two SQL values in a new array

I am brand new to PHP and I am looking to perform two SELECT COUNT queries on a MySQL column, and then store the results in an array. However, the code I have written is not functioning correctly. // Establish DB connection $link = mysqli_connect("local ...

The Angular 1.x Ajax request is not triggering the expected update in the view

I am encountering an issue with my Angular application where the data retrieved from a JSON file is not updating in the view when the JSON file is updated. It seems like the JSON file and the view are out of sync. As a newcomer to Angular, I am struggling ...

Can you combine the values of a mixed data type dictionary in Python to calculate the total sum?

I have a JSON file with values in a dictionary, and I am hoping to calculate the sum of all the numeric values. However, some of the values are not numbers but different data types. My goal is to only add up the values that are numeric. {"id": &q ...

Dealing with JSON POST requests in PHP while implementing SHA1 Encryption

I'm currently working with a REST API that sends a POST request to my server in JSON format. Here is the data it includes: info: { id: "9890dsds8", number: 5, amount: 33 }, sig: "8jhjbhb78979899h" The sig value is a SHA1 signature of the info object ...

Transforming unprocessed text into a regular string in the Rust programming language

I've been working on decoding raw bytes using base64::decode and I keep getting output that looks like {"foo":1,"bar":"first"}. However, serde_json requires the format to be { "foo":1, "bar":"first" } So, I am tasked with converting let raw = r#"{"fo ...

Transform unorganized data dumps into well-structured JSON format

The document I am reviewing contains the following data: {'What': {'top': query value 0 what time is it 100 1 what to watch 37 2 what is my ip 17 3 ...

Validating a collection of related objects within an array using JSON Schema

Which specific keyword should be utilized in a JSON Schema to ensure that all elements of an array (which are all objects) adhere to the same schema? Illustration: "data": [ { //validated "id": 1, "name": "Bob", "ready": "Not Ready ...

several mandatory fields in the json schema

In my schema, I have a required property that is dependent on an enumeration matching a certain value. This aspect of the schema is functioning as expected. "oneOf": [ { "not" : { "properties": { ...

Utilizing PowerShell to Retrieve Shopify JSON Data through the API (Experiencing a 401 Error with Invoke-Webrequest)

I am currently working on writing a PowerShell script to interact with Shopify's API and retrieve JSON data. I have set up a private app, and successfully accessed a JSON feed via a browser. Initially, I managed to make it work using System.Net.WebCli ...

The Sequence of My Configuration File Gets Altered Upon Employing Json.load

I have been searching for a solution to this problem, but I haven't found one yet. I've developed a user interface that runs using a .config file. My code successfully retrieves all the required information and everything works smoothly. Currentl ...

Utilizing JavaScript Fetch with User Input to Integrate OpenWeather API Retains Previous Data on HTML Page

I have been working with JavaScript Fetch to retrieve data from the OpenWeather API. In my project, I have created a form where users can input the name of a city to view its weather information. However, I am facing an issue where the data from the previo ...

Guidelines on fetching API data in React JS

When attempting to retrieve data from the OpenWeather API, I encountered an issue. The API's response is expected to be in JSON format, but instead, I received an error message: SyntaxError: Unexpected token < in JSON at position 0 useEffect(() =& ...

What is the reason for the denial of JSON permission within a Linux user's account?

Encountering issues with Laravel installation on Ubuntu 18.04 [ErrorException] Unable to create file (./composer.json): Permission denied ...

Accessing Key / Value pairs of a JSON object using Newtonsoft Library

I've come across several questions and answers related to my current task, but despite reading through the responses, I'm still struggling to extract the key and value from this JSON. Here's the JSON data that is being returned: { "@odata. ...