Converting JSON Data to Java Object

I need some help with a specific issue I'm encountering.

I have retrieved a JSON string from MongoDB and I am trying to extract all the values of 'photo' and store them in an ArrayList. Despite finding examples online, I haven't been successful in making them work. I am currently using GSON for this task, but even a solution based on pure JSON would be acceptable.

The data returned from MongoDB is as follows:

  [ { "url" : "/photos/avatar-1.jpg" , "photo" : "avatar-1.jpg" , "description" : "test     1"} , { "url" : "/photos/avatar-2.jpg" , "photo" : "avatar-2.jpg" , "description" : "test 2"} , { "url" : "/photos/avatar-3.jpg" , "photo" : "avatar-3.jpg" , "description" : "test 3"} , { "url" : "/photos/avatar-4.jpg" , "photo" : "avatar-4.jpg" , "description" : "test 4"}]

Adding the values to an ArrayList isn't an issue, it's extracting the 'photo' value that's proving challenging. If anyone could provide me with a sample code that demonstrates how to iterate through the 4 arrays and print out the 'photo' value using System.out.println, I would greatly appreciate it!

Thank you!

Answer №1

jsonString = [...];
Gson gson = new Gson();
PhotoDTO[] photos = gson.fromJson(jsonString, PhotoDTO[].class);

for(PhotoDTO photo : photos){
   System.out.println("photo -> " + photo.getPhoto());
}

PhotoDTO Class Structure

class PhotoDTO
{
  String url;
  String photo;
  String description;
  // methods for setting and getting values
}

Answer №2

To handle JSON data efficiently, consider utilizing the json-simple library available at this link. Here's an example of how you can use it:

String jsonData = "[{\"photo\": \"1.png\"}, {\"photo\": \"2.png\"}, " +
                "{\"photo\": \"3.png\"}, {\"photo\": \"4.png\"}]";
JSONArray photosArray = (JSONArray)JSONValue.parse(jsonData);
for (int i = 0; i < photosArray.size(); i++) {
    JSONObject photoObject = (JSONObject)photosArray.get(i);
    System.out.println(photoObject.get("photo"));
}

Remember to replace the hardcoded JSON text with the actual data retrieved from your database.

Answer №3

A different approach that eliminates the need to create DTOs involves utilizing the Gson library's StringMap class:

String json = "[ { \"url\" : \"/photos/avatar-1.jpg\" , \"photo\" : \"avatar-1.jpg\" , \"description\" : \"test     1\"} , { \"url\" : \"/photos/avatar-2.jpg\" , \"photo\" : \"avatar-2.jpg\" , \"description\" : \"test 2\"} , { \"url\" : \"/photos/avatar-3.jpg\" , \"photo\" : \"avatar-3.jpg\" , \"description\" : \"test 3\"} , { \"url\" : \"/photos/avatar-4.jpg\" , \"photo\" : \"avatar-4.jpg\" , \"description\" : \"test 4\"}]";   

Gson gson = new Gson();     
Type type = new TypeToken<List<StringMap<String>>>(){}.getType();
List<StringMap<String>> stringMaps = gson.fromJson(json, type);
for (StringMap<String> map:stringMaps) {
    System.out.println(map.get("photo"));
}

UPDATE

Required Imports:

import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;

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

I've been encountering an issue with the WebClient.DownLoadString function where it inserts """ in front of each element of my JSON data. Is there a way to properly parse the

In my MVC application, I am facing an issue while trying to access a REST Service. I am using the getJSON method to retrieve data from a controller, which internally calls the REST service and returns data in JSON format. However, when executing the Downlo ...

Is there a way to convert the structure of HTML/CSS into JSON format?

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .collapsible { background-color: #004c97; color: white; cursor: pointer; padding: 18px; width: 100%; border: none; text ...

Using Selenium Webdriver to upload a file to a website

What is the process for automating jpeg uploads on a UI? Currently, I have the image stored in my repository under resources and using this code: WebElement element = driver.findElement(By.id("mypicId")); File file = new File(ClassLoader.getSystemResourc ...

Tips for building a dynamic panel with an AjaxLink in Wicket?

I have been attempting to create multiple links that will update a table within a website using an AjaxLink from Wicket. Despite setting "setOutputMarkupId(true)" and using methods like "setDefaultModelObject" and "addComponent", the table remains unchange ...

Looking for dates within JSON data using Python

Seeking advice on efficiently searching through JSON data to find today's date/time and retrieve the corresponding value. Here is a snippet of the JSON data structure: [ { "startDateTime": "2018-04-11T14:17:00-05:00", "endDateTim ...

What is the process of transforming the character u0421 into the letter "C"?

After making a post query to the server, I received JSON data that had an incorrect symbol: instead of "Correct," it showed up as "\u0421orrect". How can I properly encode this text? The function parse_json appeared to handle it like "РЎorrect"; T ...

What is the best way to convert a JSON object into a string containing a negative zero in JavaScript?

Is there a way to properly convert a negative zero into a string using JSON.stringify? I've noticed that JSON.stringify often converts negative zero into a positive one, which is not the desired outcome. Any suggestions for an alternative approach? v ...

Ways to rerun a test suite in TestNG without relying on a listener

I needed to find a way to re-run an entire TestNG test suite from the test method itself if any of the test cases failed. Is it possible to trigger the complete suite to run using an XML file or within the Test class in the test method? The re-run should i ...

Using React to visualize data from Node.js in Chart.js

My Node.js application fetches a JSON object from a MySQL database and I want to display it in real-time using Chart.js and React. Here is the code snippet for fetching the JSON data from the MySQL database (script.js): const mysql=require('mysql&apo ...

Avoiding URL Error by Leveraging API for Cover Retrieval

I am facing an issue with my PHP website where I am unable to retrieve album covers. Previously, I used a JSON to obtain the Album ID and then used that ID to fetch the corresponding album cover. The problem now is that when I try to decode the JSON from ...

Ways to eliminate unnecessary quotation marks surrounding a string in a JSON file using a shell script

I need help removing extra quotation marks from the following JSON data: {""id"":""1"", ""name"":""john"",""address"":"",""timestamp"":""2018/01/01 12:43:42 -700"",""dept"":""} To address this issue, I have been using the sed command: sed -i -e 's/ ...

An efficient method for extracting targeted information from a JSON encoded string

While working on some code, I encountered the following output when echoing this piece of code: echo json_encode($_SERVER); Output Received: { "HTTP_CONTENT_TYPE":"application\/x-www-form-urlencoded", "HTTP_USER_AGENT ...

Flatten a multidimensional array in PHP while preserving keys

I have written some PHP code to organize the children of an array using a recursive function. While everything is displayed correctly in one column, some arrays are missing the "Name" key. Does anyone know how I can ensure that all elements display their ...

Guide to swapping out the variables "labels" in JavaScript

Here is the object structure: { 'File_12345.ZLM': { MeterID_12345: { BASIC_INFO: [Object] } } } { 'File_678910.ZLM': { MeterID_678910: { BASIC_INFO: [Object], } } } ======================== ...

What is the best way to display a particular category in a RecyclerView by parsing data from a JSON

I am looking to populate a RecyclerView with project data from a specific category only. For instance, in the JSON provided, there are 2 projects in the "Cabs" category, so I want to include only these 2 projects. Conversely, if the category is equal to "T ...

Unraveling JSON through DOJO AJAX and REST techniques

I have been attempting to send a request to a REST server using DOJO AJAX, but unfortunately I am receiving a null object as the result in the console: When CLICKED = click clientX=34, clientY=13 JSON loaded from server: null Below is the code snippet I ...

Managing a unique section within package.json

Having a custom section in my package.json file is something I'm currently working with. Here's an example structure: { "name": "foo", "version": "0.0.1", "dependencies": { ... }, "mySection": { ... } } Retrieving the data from this cus ...

What is the best way to update a React state with JSON data?

Currently, I am dealing with a React component that sends a post request to an Express server hosted by myself. The server employs web3 for signing transactions on the Ethereum blockchain. Upon successful inclusion of the transaction in a block, a JSON obj ...

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...

Encountered an issue while setting up the MongoDB dependencies for the Node.js application

Looking for assistance with this error message encountered during package installation: "unexpected end of JSON input." You can check out the log file here. Here's a glimpse of the log file while installing the MongoDB package: 0 info it worked i ...