Having trouble extracting JSON data from an API in a Flutter application

My goal is to retrieve and parse JSON data from a REST API in node.js using express and MongoDB, and then present it as userdata. However, no matter what I attempt, I am unable to successfully parse the data. It either throws an exception like "Unhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap' has no instance method 'cast' with matching arguments," or it simply displays null. The JSON data that I am trying to parse looks like this:

{"userData":{"_id":"5d3c29fdb1b0fd22182ae683","personName":"Damian","userIdentificationEMAIL":"[email protected]","dateofbirth":"14.07.2000","grad":"Los Angeles","postanskibroj":"2B","ulica":"Jackovina","drzava":"California","faiID":"123456789","nacionalniID":"000"},"request":{"type":"GET","url":"http://localhost:3000/products"}}

The "request" field in the JSON data is not actually necessary for anything - some have suggested that it is falsely referenced. Additionally, if helpful, I can place the entire "userData" in an array when fetched from the API.

I have attempted to use Quicktype without success, along with various examples and methods found on Stack Overflow and other sources. Unfortunately, none of these approaches have yielded positive results.

Although I am able to obtain the data from the API, I am struggling to properly parse it and subsequently display the user's information.

In essence, my objective is to successfully parse the data, display it in a list or text format, store it in a variable, and utilize it throughout the application. Any assistance would be greatly appreciated. Thank you and cheers!

Answer №1

By making the necessary changes to the JSON text and converting it into a JSON array, your code will function correctly.

To enhance the elegance of your code, consider modifying the factory constructor as shown below:

  factory UserData.fromJson(Map<String, dynamic> json) => UserData(
        userData: json["userData"]
            .map<UserDatum>((x) => UserDatum.fromJson(x))
            .toList(),
        request: Request.fromJson(json["request"]),
      );

You can access fields like this:

  print(UserData.fromJson(decode).userData[0].dateofbirth);

Answer №2

There seems to be a syntax error in your json data.

I have analyzed the data you provided with the question.

To assist you, try generating dart code for your classes by visiting this link

You will receive an Autogenerated Class initially followed by its sub classes.

UPDATE


Since you have updated the question and posted error-free json code, I have made slight changes to the answer


If you decide to rename the Autogenerated class, ensure to also update it in the method below

Then proceed to pass your json data to the function as shown

fetchData() async{
  Response response;
  response = await get("yourURL");
  var json = jsonDecode(response.body);
  List<Autogenerated> _userDataList = Autogenerated.fromJson(json); 
}

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

Combining JSON files in R: A Guide

I am currently attempting to combine 380 JSON files into a single dataframe. Here is the code I have written for this task, but I keep encountering errors: library(jsonlite) multmerge <- function(mypath) {filenames=list.files(path=mypath, full.names ...

What is the best way to convert a graphql query into a JSON object?

I'm facing an issue where I need to convert a GraphQL query into a JSON object. Essentially, I have a query structured like the example below, and I'm seeking a method to obtain a JSON representation of this query. Despite my efforts in searching ...

Attempting to comprehend the error message "TypeError: list indices must be integers or slices, not str"

### The following line executes without errors health_data_json = resp.json()["data"]["metrics"] ### However, this line results in a "TypeError: list indices must be integers or slices, not str" message energy_data_json = resp.json()[ ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

methods for removing white spaces from json webservice output in asp.net

Hello everyone! I'm new to the world of JSON and this is my first experience with a webservice. I have successfully created an ASP.NET Webservice that returns JSON data. Everything seems to be working fine, but there is one issue I need help with. Wh ...

Troubleshooting: jQuery AJAX failing to receive JSON data in HTTP request

Experimenting with HTML and jQuery to practice JSON requests, I conducted some research and attempted a small test. However, upon running the script in Google Chrome, only my HTML/CSS elements appeared instead of expected results. Below is the code snippet ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Is there a way to eliminate the landing dashboard from the list of dashboards in Grafana?

I am looking to create a dashboard panel that displays all dashboards except for one specific landing page that I do not want included in the list. Although I attempted to modify the JSON code, I struggled to find a solution to this issue. The current pa ...

Retrieve data from a MongoDB collection based on a specific index field

I am looking to extract only the "thetext" field from a specific index in my database when the value of "comment_count" is 1. This is the query I have tried: db.getCollection('mongotesi').find({},{'bug.long_desc.1.thetext':'1&apo ...

Creating SQL server tables from JSON automatically in C#

Users are sending me JSON Form Data. Here is an example of the data: { "Name":"Mike", "Age":25, "Gender":"Male", "Skills":{ ".Net":true, "Mule":"" } } I need to save this data in a table on SQL Server, but there isn't ...

Retrieving JSON information from a URI in PHP without relying on cURL

Recently, I encountered a scenario where I needed to retrieve data from a URI returned in JSON format on my IIS machine with PHP. The specific URL was: The challenge was that I couldn't utilize cURL for this task. Is there an alternate method to acco ...

DataTables: Reordering array elements while rendering

When utilizing DataTables with server-side processing, I encounter a json object that contains an array of LocalDateTime elements: ... "SimpleDate": [ 2000,12,31,0,0 ] ... In the initialization script, my columns definition is as follows: "columns": [ ...

Incorporate and interpret a custom JSON object within my Shopify Liquid theme

In an attempt to integrate custom data into my Shopify liquid theme, I stored a JSON file in the assets folder. My goal is to retrieve and parse this JSON object within a jQuery method from a JavaScript file also located in the assets folder. Despite try ...

Adding parameters to TR or TDs in DataTables 1.10.5 via Ajax: A step-by-step guide

My goal is to dynamically load datatable data using AJAX and customize the rows and cells by adding parameters such as classes or 'data' attributes. The challenge lies in utilizing a PHP helper that generates JavaScript code, as shown below: $da ...

Adding map markers from a JSON feed to your React Google Map - a step-by-step guide!

I'm currently working on a React project that involves integrating Google Maps: const MarkerComponent = ({text}) => <div>{text}</div>; export default class NavMap extends Component { constructor(props) { super(props); this.s ...

How to Send and Receive Data in One Request Using Android Studio and Web API

Currently, I am working on an Android App using Android Studio and the backend is being developed using Asp.Net Web API. Web Api Part [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public dynamic GetTest(string name) { List< ...

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 ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

Steps for adding JSON array information to the tbody of an HTML table

I am a beginner in the world of jQuery and JSON, seeking guidance on parsing a JSON file in order to populate an HTML table's tbody section: {"response":[["name0","id0","amt0"],["name1","id1","amt1"]]} I am struggling to figure out how to access thi ...