What is the process for converting an attribute ArrayList<String>, ArrayList<Integer>, or ArrayList<MYCLASS> from a JSON object into a Java object?

Being a novice in programming, I am currently attempting to save my objects as JSON in a text file. However, I have encountered difficulties when passing the JSON object to my constructor.

Here is the structure of my 'Aluno' class:

public class Aluno {
protected String matricula;
protected ArrayList<Integer> concluidas;
protected ArrayList<Integer> cursando;
protected ArrayList<Notas> notas;

This method is used to convert the class to JSON:

public JSONObject toJson(){
JSONObject json = new JSONObject();
json.put("matricula",this.matricula);
json.put("concluidas",this.concluidas);
json.put("notas",this.notas);
return json; }

The issue lies within the constructor:

public Aluno(JSONObject json) {
    this.matricula = json.getString("matricula");
    this.concluidas = (ArrayList<Integer>) json.get("concluidas");

    this.notas = (ArrayList<Notas>) json.get("notas");


    this.cursando = (ArrayList<Integer>) json.get("cursando");
}

An error is triggered at this line:

this.concluidas = (ArrayList<Integer>) json.get("concluidas");

ERROR : Exception in thread "main" java.lang.ClassCastException: json.JSONArray cannot be cast to java.util.ArrayList

A similar issue occurs with the 'cursando' and 'notas' ArrayLists.

Answer №1

ArrayList<Integer> finishedTasks = new ArrayList<Integer>();     
JSONArray jArray = (JSONArray)json.get("concluidas");; 
if (jArray != null) { 
   for (int i=0;i<jArray.length();i++){ 
    listdata.add(jArray.getInt(i));
   } 
} 

You can apply the same logic to handle other JSONArrays as well.

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

Resulting JSON output retrieved from the database

Greetings! I have retrieved the JSON data below from my database: [{ "0": "1", "id": "1", "1": "Hakob", "name": "Hakob", "2": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8f8c8dae8b838f8782c08d8183"> ...

Obtain numerous JSON pages using jq

When making an API call, I receive a JSON response that can be formatted nicely using curl "https://mywebsite.com/api/cars.json&page=1" | jq '.' Displayed below is a sample of the output. Since there are multiple pages of data (112 total ...

JSONP Error - "SyntaxError: Unexpected token caught"

Just to start off, I want to mention that I'm new to working with jsonp. This is my first time diving into the world of JSONP. Currently, I'm using a jQuery ajax call to retrieve data from a website. Here's a snippet of my jQuery code: $. ...

Having difficulties uploading a file with an AutoIT script

I have been searching extensively without success. My problem is that I've written an AutoIT script that works perfectly when executed independently from C# or Java code. Here's the script: WinWaitActive("File Upload") Send("C:\Users\f ...

Unraveling the mystery of deciphering Google Search API outcomes

I am facing an issue with inserting Google search results into a MySQL database encoded in utf-8. When I check the inserted rows, some characters appear strange. For instance, "doctor's handbook" shows up as "doctor&#39;s handbook". I have tried u ...

Utilize anychart.js to define the axis using JSON data

I'm relatively new to using anychart js and encountering some obstacles. I have a json file that is being fetched from an API, containing data on NBA players' statistics. You can find the json file here: My goal is to display the date data on th ...

Encountering a serialization error when trying to load a JSON file

Below is a JSON file example: [ { "applicationConfig": { "Name": "Name1", "Site": "Site1" }, "pathConfig": { "SourcePath": "C:\\Temp\\Outgoing1", "TargetPath": "C:\\Files" }, "cre ...

Extract data from a JSON-encoded array using JavaScript

I sent a JSON encoded array to JavaScript. Now I want to access that array to retrieve the different elements. When I print it out using console.log(), I see this array: array(1) { [16]=> array(2) { [3488]=> array(1) { [0]=> ...

Ajax transmitting data with concealed characters

I'm trying to send data from one PHP site to another. On the first site, everything looks good. The string appears as --show="author,book,text/n However, when I check the string after receiving it on the second site, it shows --show="author,b ...

Error: JSON Exception - Value Not Found

Having some issues, as shown in the logcat below: D/JSON Parser: ����������µM @@ÿJÌYÁ5õfyo]"dÄM]wÅ] ÿ{kXôuí4ð�... ña,-8vbðp@botS â¯&©V ±4Ý~HÌBSBÓ N<sN{UÑãHIrR`ÊN´AÓ... E/JSON Parser:E ...

Unraveling complex JSON data within a dataframe using R, including tackling regular expression challenges

I am a beginner in R and I am facing an issue. I have imported a JSON file and converted it to a dataframe. Now, I need to filter rows based on certain conditions: In the image attached, you can see that there is a column recording hours (payload.hours). ...

How can you delete an element attribute using JavascriptExecutor in Selenium WebDriver?

I am currently facing an issue with setting up an auto bid on an auction site. The problem lies in the fact that the confirm button remains disabled until the user enters keypresses into the text field. Although I can populate the field using selenium.type ...

Dealing with data manipulation in the realm of javascript

In the following code snippet, I am iterating through multiple URLs and extracting data (title and content) from each of them. My objective is to store this data for later use on another page, and thus it needs to be accessible using its respective title, ...

How can I utilize "convert-excel-to-json" to extract a specific value from an Excel sheet and store it in a variable?

Currently, I am in the process of learning how to utilize the installed npm module "convert-excel-to-json" to extract a single cell value from an Excel sheet and store it in a variable using Node.js. Within my Excel workbook, there are 8 values ranging fro ...

File attachments using Selenium Webdriver

Currently, I am conducting automated testing using Selenium WebDriver in Eclipse. The challenge I am facing is the requirement to upload actual files and send them during the tests. However, storing these files on my local drive is not an option as the f ...

Acquiring the console log data from Firefox version 43 using Selenium, all without the use of any

Can Selenium retrieve the console.log from browsers like Firefox 43? If so, how can it be done? My settings are as follows: DesiredCapabilities capabilities = DesiredCapabilities.firefox(); LoggingPreferences logs = new LoggingPreferences(); logs.enable( ...

JSON does not transmit data via post requests

I have a question regarding JSON. Initially, I created this jQuery code: <script> $('#buy').click(function(){ var items=[]; var item={ firstname:'blabla' ...

Using React to Dynamically Display JSON Data as HTML

Struggling to incorporate HTML rendering from JSON data into my React component without relying on dangerouslySetInnerHTML. I want to include other React components within the rendered HTML, but facing challenges when trying to render multiple elements or ...

Having trouble pinpointing the source of the error and finding a solution

*While attempting to parse some data through JSON, I encountered an issue where clicking on a specific button caused the parsing activity to stop working. The rest of the app is functioning properly except for this particular button.* Main Activity Button ...

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...