Exploring the automated retrieval of data from arrays in Java objects: A comprehensive guide

My goal is to automatically create Java objects from JSON data obtained from a REST API. The JSON array contains properties of different shops, and I aim to generate one object per shop with all its respective properties.

The following code helped me achieve this:

ArrayList<Magasin> objMag= new ArrayList<Magasin>();
                JSONArray databrute = new JSONArray(sortie);
                for (int i = 0; i < databrute.length(); i++){
                    ville = databrute.getJSONObject(i).getString("ville");
                    nom = databrute.getJSONObject(i).getString("nom");
                    objMag.add(new Magasin(ville,nom/*,rue,type,descrp,createur,statutlegal,datecreat,datemodif,magcreat,codepost,id,nbemployes,turnover1,turnover2*/));
                }
                System.out.println(objMag.get(2).getVille);

            }

If we consider the following (long) JSON dataset:

[
// JSON data
]

I anticipated having 4 generated objects ([Magasin@1d81eb93, Magasin@7291c18f, Magasin@34a245ab, Magasin@7cc355be]) when printing the objMag array. However, when trying to access specific data from an object like Magasin@34a245ab using

System.out.println(objMag.get(2).getVille);
, it always returns data from Magasin@1d81eb93. How can I access data from the other objects? Is there an issue with how I'm generating these objects?

Answer №1

To quickly resolve your issue, using org.apache.commons.io.IOUtils along with com.fasterxml.jackson.databind.ObjectMapper is recommended.

Consider the following code snippet:

class MegaSinList{
    private List<MegaSin> megasinList;
}

class MegaSin{
    private String codePostale;
    private String createur;
    private String creationDate;
    private String creationShop;
    private String description;
    private int identifiant;
    private String modification;
    private String nom;
    private int nombreEmploye;
    private String rue;
    private String statutLegal;
    private long turnOverRange1;
    private long turnOverRange2;
    private String type;
    private String ville;
}

and utilize the function below to extract data:

byte[] jsonData = IOUtils.toByteArray("/...filepath../file.json").getInputStream());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
MegaSinList magasinListObj = objectMapper.readValue(jsonData, MegaSinList.class);
return magasinListObj;

Keep in mind that depending on the json structure, ObjectMapper may return a list of LinkedHashMap containing key-value pairs. In such cases, you may need to retrieve data using map.get("key") from the list and assign it to the desired object.

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

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Using the `ng-if` directive in Angular to check for the

I need to output data in JSON format using items. To display a single item, I utilize ng-repeat="item in items". Additionally, I can access the user object of the currently logged-in user with user. Every item has the ability to belong to multiple wishlis ...

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

What is the best way to sort my API responses to display only users who are either currently online or offline?

Hi everyone, I've made great progress on my project so far without any assistance (pretty proud of myself), but now I could use some help. I'm working on creating a tabbed menu that filters the results of my API calls to display: All users, Onlin ...

"Executing a SQL command that involves a JSON data type column

Currently, I am dealing with a table called individual customer that contains a column named employmentDetails which stores data in JSON format. My objective is to retrieve customers who have an empty locality field. [{ "employmentStatus": " ...

Tips on efficiently compressing JSON data in order to receive it using the bodyParser.json method

I am looking to compress a JSON file before sending it to my server. I want to handle the compression in the browser by utilizing an explainer and then pass it to the bodyParser.json middleware. The client-side function would look something like this: e ...

transforming a string into a pandas dataframe using Python

I have a String variable with data that I would like to convert into a data frame using Python. I need someone to provide guidance on how to proceed. Data : data1 Name Space -------------------- ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

What is a way to perform pre-increment without utilizing the ++I operator?

It is my belief that the code snippet below: i += 1 or i = i + 1 does not have the same effect as ++i. Am I incorrect in this assumption? Is there an alternative method to achieve pre-increment without utilizing the ++ operator? ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

Deleting an element from an array in JavaScript

I am working with a JavaScript array that I need to store in local storage. var myArray; myArray = [1,2,3,4,5]; localStorage.setItem('myArray', JSON.stringify(myArray)); The above code snippet sets the values of the 'myArray' ...

Transforming a Pyspark dataframe into the desired JSON structure

Is there a way to convert a Pyspark dataframe into a specific JSON format without the need to convert it to a Python pandas dataframe? Here is an example of our input Pyspark df: model year timestamp 0 i20 [2019, 2018 ...

Implementing parallel execution with POM (Page Factory) for updating records

Looking for some help as I couldn't find a solution to my issue. I'm having trouble running tests in parallel using POM with page factory. *\ Testbase class */ public WebDriver driver; @BeforeClass @Parameters("Browsername&qu ...

"Why don't JSON support comments? It seems like developers used to communicate instructions to the parser using them." Can someone clarify this concept for me?

Can someone help me understand why Comments are removed in JSON even though some parsers can read them? Douglas Crawford mentioned that it's to prevent passing instructions to parsers through comments. Does anyone have more insight on this? ...

Could it be possible that my code is preventing any duplicate entries in a table?

Currently, I am in the process of developing an application that utilizes JSON data which is regularly updated with fresh JSON data from a Delphi application that I am concurrently working on. Below is the stored procedure I have created to import this inf ...

What method does `JSONDecoder` utilize to determine the appropriate encoding to apply?

After reading Joel on Encoding like a diligent reader, I am puzzled by the inner workings of Foundation's JSONDecoder. I noticed that neither the init nor decode methods include an encoding value. Is it possible that the dataDecodingStrategy instance ...

Tips for instructing SharePoint 2010 listdata.svc to provide JSON through the URL

I require the JSON response from the following unique URL: After referring to a reputable online source, I attempted to modify the URL with additional parameters but unfortunately, it did not yield the desired outcome. The altered URL looked like this: D ...

A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows: [{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}] To loop through this retrieved object, I use the following ...

Error: JSON parsing encountered an unexpected character "D" at position 1

When I call a python script as a child process from my node.js app to extract data from an uploaded file, I encounter the error 'UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token D in JSON at position 1" when uploading the file thro ...