Handling various JSON responses in Java without relying on Plain Old Java Objects (POJO) classes

I am working with JSON responses from a REST API in Java, but I am looking for a solution that doesn't require creating a Java class (POJO) for each response due to the varying data structures and fields. Is there a more versatile JSON parser in Java that offers a syntax similar to JavaScript's simplicity?

The following JSON represents one example of the many responses from different REST endpoints

{
    "f1" : "volume",
    "f2" : "gender",
    "f3" : "days",
    "f4" : [{
            "id" : "F",
            "name" : "female",
            "values" : [{
                    "name" : "September",
                    "value" : 12
                }
            ]
        }, {
            "id" : "M",
            "name" : "male",
            "values" : [{
                    "name" : "September",
                    "value" : 11
                }
            ]
        }
    ]
}

In JavaScript, you can access the value for female like this:

jsonRoot.f4[0].values[0].value

This approach is cleaner than creating numerous Java classes. Do you have any suggestions for a similar solution or a way to avoid generating multiple POJOs?

Answer №1

When utilizing the com.google.gson jar, extracting a value can be achieved in the following manner:

     String str="{" +
            "    \"f1\" : \"volume\"," +
            "    \"f2\" : \"gender\"," +
            "    \"f3\" : \"days\"," +
            "    \"f4\" : [{" +
            "            \"id\" : \"F\"," +
            "            \"name\" : \"female\"," +
            "            \"values\" : [{" +
            "                    \"name\" : \"September\"," +
            "                    \"value\" : 12" +
            "                }" +
            "            ]" +
            "        }, {" +
            "            \"id\" : \"M\"," +
            "            \"name\" : \"male\"," +
            "            \"values\" : [{" +
            "                    \"name\" : \"September\"," +
            "                    \"value\" : 11" +
            "                }" +
            "            ]" +
            "        }" +
            "    ]" +
            "}";
    JsonParser parser=new JsonParser();
    JsonObject object=(JsonObject)parser.parse(str);
    String value=object.get("f4").getAsJsonArray().get(0).getAsJsonObject()
            .get("values").getAsJsonArray().get(0).getAsJsonObject()
            .get("value").getAsString();

Answer №2

Using Jackson to map to a Map<String, Object> is an acceptable approach:

    String jsonData = "{\"f4\":[1, 2]}"

    try {
        Map<String, Object> mappedValue = mapper.readValue(jsonData, Map.class);
        System.out.println(mappedValue.get("f4"));
    } catch (IOException ex) {
        ex.printStackTrace();
    } 

Creating a POJO object for this purpose provides static type checking, and I advise doing so.

Answer №3

    String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
    Object obj=JSONValue.parse(s);
    JSONArray array=(JSONArray)obj;
    System.out.println(array.get(1));       
    System.out.println(((JSONObject)array.get(1)).get("1"));

explore more examples here

download json-simple.jar

Answer №4

The org.json library can be utilized for this purpose.

If you are using Maven:

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20150729</version>
    </dependency>

Alternatively, you can download the JAR file from: http://mvnrepository.com/artifact/org.json/json

Here is a Java example:

import org.json.JSONObject;

public class JSONExample {

    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject("{'f1' : 'volume', 'f2' : 'gender', 'f3' : 'days'}"); // Truncated for demonstration purposes

        String f1Value = jsonObject.getString("f1");
        System.out.println(f1Value);
    }
}

You can also access arrays:

JSONArray f4Array = jsonObject.getJSONArray("f4");

Then iterate over the array elements:

for (int i = 0; i < f4Array.length(); i++){
        String id = f4Array.getJSONObject(i).getString("id");
        String name = f4Array.getJSONObject(i).getString("name");
        System.out.println(name);
        System.out.println(id);
        JSONArray values = f4Array.getJSONObject(i).getJSONArray("values");
        for (int j = 0; j < values.length(); j++){
            String valueName = values.getJSONObject(j).getString("name");
            int numValue = values.getJSONObject(j).getInt("value");
            System.out.println(valueName);
            System.out.println(numValue);
        }

    }

Answer №5

If you're utilizing jQuery, remember that there's a parseJson() function available for data parsing.

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

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...

Encountering an issue when bundling an application using electron-forge: "Unable to find solution for './→' "

Having trouble packaging my Electron application using electron-forge. It seems like the issue lies with native modules such as 'sqlite3'. Upon running the command npm run package, I encounter this error: Module not found: Error: Can't reso ...

What causes asymmetry in decoding and encoding Strings in Java?

I'm experiencing some confusion when it comes to decoding and encoding Java Strings. Let's consider a string variable "中国" which translates to China in Chinese. This string is in the Chinese native charset GB2312, as well as Unicode. What e ...

Retrieve the data stored in a ListItem and transfer it to the succeeding Activity

As someone who is relatively new to the world of Eclipse and ADT plugin, I would greatly appreciate it if any answers could include an explanation of what is happening. It would be incredibly helpful. Essentially, I have a list within one activity that wi ...

Using Node.js to Send Parameters in a POST Request

I have a node.js application with an express framework and a POST route defined as follows: app.post('/test', function(req, res){ //res.send(req.body.title + req.body.body) console.log(req.params); console.log(req.body); console.log(req.bod ...

Converting an HTML menu to a WordPress menu: A step-by-step guide

Hey everyone, I've got some code in my HTML file that's using the 320 Bootstrap WP theme. I've created a menu and it's working fine. However, the box above the menu isn't moving along with it from menu to menu. Any ideas on how to ...

How do apps benefit from Android optimization?

During the android update process, the system also 'optimizes' apps which can be time-consuming. I often think about whether this optimization involves changing binaries to enhance performance. How does this affect developers? Essentially, my que ...

How can we use JavaScript to create visual representations of data pulled from a JSON file?

I am interested in utilizing a library similar to the Google Visualization API for creating charts, but with the ability to retrieve data as JSON from an external source. Specifically, I intend to use an SPARQL service to extract information from an XHTML+ ...

Navigating with Angular in SailsJS

Working with sailjs and angular has been causing me some issues. Specifically, when I make a GET request using the URL cate/:id/new, my link ends up looking like http://localhost:1337/category/5540ba9975492b9155e03836/new How does angular recognize my ID ...

There is no 'Access-Control-Allow-Origin' header on the requested resource when connecting to a Heroku server

After deploying a Node.js + Express server to Heroku, I encountered an error while trying to use it: "Access to XMLHttpRequest at 'https://harel-shop-backend.herokuapp.com/auth/autologin' from origin 'http://localhost:3000' has ...

Using JavaScript to determine the time it will take to download something

Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...

Troubleshooting problem with Angular 2 in Internet Explorer related to the use of [style]="

I've encountered a challenge while using angular 2 (2.0.0-beta.17). The app works perfectly on most browsers, but as expected, IE 11 is causing trouble. The scripts included in the head for angular are: <script type='text/javascript' sr ...

Swapping React components within a list: How to easily change classes

For my latest project, I am building a straightforward ecommerce website. One of the key features on the product page is the ability for users to select different attributes such as sizes and colors. These options are represented by clickable divs that pul ...

MVC5 Toggle Button for Instant Display and Concealment

I used to utilize this method in Web Form development by targeting the id and name of the input radio button. However, I am encountering difficulties implementing it in MVC5. Can someone kindly point out where I might be going wrong? Upon selecting a radi ...

Filtering data within a specific date range on an HTML table using JavaScript

I am attempting to implement a date filtering feature on my HTML table. Users should be able to input two dates (From and To) and the data in the "Date Column" of the table will be filtered accordingly. The inputs on the page are: <input type="date" i ...

Is there a way to use HTML and JS to draw custom lines connecting elements?

Sorry if this question has been asked before. Is there a way to create straight lines connecting HTML elements with just HTML and JavaScript, without relying on SVG or Canvas? If so, what would be the most effective approach? ...

No content appears on the multi-form component in React

After several attempts at building a multi-step form in React, I initially created a convoluted version using React.Component with numerous condition tests to determine which form to display. Unsatisfied with this approach, I decided to refactor the code f ...

The modal window displays an error upon submission and prevents itself from closing

Below is the HTML code for a modal form: <form action="" class="cd-form" method="POST" id="signinform" onsubmit="return: false;"> <p class="fieldset" id="warningPanel"> <?php ShowAlertWarning(); ?> </p> <p ...

Obtaining nested objects from a MongoDB document's array using Spring Data

Mongo document 'History': @Document(collection = "histories") @Data public class History { @Id private String id; @Transient private final String name = MAIN_FOLDER; private String appleId; private ArrayList< ...

What is the process for uploading or hosting a Reactjs website?

Currently, I am in the process of developing a React web application project using create-react-app. The project is nearly complete and as part of my preparation, I have been researching how to obtain a hostname. During my research, I came across https://w ...