Guide on decoding JSON data in Java: retrieving JSON data from a local server and displaying its contents

My current project involves working on a basic example of encoding and decoding JSON using Java. The goal is to send signup page details to a JavaScript function, which then encodes these values into JSON format before sending them to a servlet.

While I have managed to successfully send the data, I am facing issues with decoding (parsing) and displaying it at the servlet end. As someone who is new to both JSON and Java, my primary objective is to retrieve values from a JSON array in a servlet, which I plan to store in a database later on.

/*Sample JavaScript code snippet*/

function signup() {
   var request = createCORSRequest("GET", "http://localhost:8080/jsondem/pass");
  
    /* Retrieve input field values */
    var name = document.getElementById('name').value;
    var mobileNo = document.getElementById('mobileNo').value;
    var emailId = document.getElementById('emailId').value;
    var password = document.getElementById('password').value;
    
    alert(name);
    alert(mobileNo);
    alert(emailId);
    alert(password);
    
    /* Construct data object for JSON conversion */
    var data = {"name": name, "password": password, "mobileNo": mobileNo, "emailId": emailId};
    
    alert(JSON.stringify(data));

    var sendData = function(data){   
        alert(JSON.stringify(data));
      
        $.ajax({
            url:'http://localhost:8080/jsondem/pass',
            type: 'GET',
            contentType: 'application/json',
            data: JSON.stringify(data),
            
            success: function(response) {
                alert(response);
            },
            error: function(response) {
              alert('error'+response);
            }
        });
    };
    
    sendData(data);
}

In order to handle the JSON data received in my local server through a servlet, I have implemented the following solution:

/*Sample servlet's doGet Method*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        new JavaHttpUrlConnectionReader();
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

class JavaHttpUrlConnectionReader {

    public JavaHttpUrlConnectionReader() {
        try {
            String myUrl = "http://localhost:8080/jsondem/pass";
            myUrl = URLEncoder.encode(myUrl, "UTF-8");

            doHttpUrlConnectionAction(myUrl);

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private void doHttpUrlConnectionAction(String myUrl) throws Exception {

        URL url = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder;
        JSONParser jsonParser = new JSONParser();

        try {
            url = new URL(myUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setReadTimeout(15*1000);
            connection.connect();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

            String name = (String) jsonObject.get("name");
            System.out.println("Name: " + name);

            long mobileNo = (long) jsonObject.get("mobileNo");
            System.out.println("Mobile Number: " + mobileNo);

            String emailId = (String) jsonObject.get("emailId");
            System.out.println("Email Id: " + emailId);

            String password = (String) jsonObject.get("password");
            System.out.println("Password: " + password);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}

I have encountered some challenges in handling the output as shown below. Any assistance would be greatly appreciated. https://i.sstatic.net/MUzqH.png

Answer №1

When your JavaScript sends code to the server, you will need to handle this data on the server side within the servlet. In the servlet doGet method, you can read the data that is being sent. There is no need to make another connection to the server. Below is an example implementation of the doGet method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String name = request.getParameter("name");
    String password = request.getParameter("password");
    String mobileNumber = request.getParameter("mobileNo");
    //Continue reading any other parameters here...
}

It would be more appropriate to use the POST http method when sending data to the server. Therefore, in the servlet, you should implement doPost instead of doGet.

Answer №2

Avoid utilizing HTTP GET request when aiming to modify the server state, such as updates to data.

step1: Replace your $.get with $.post step2: Validate if the request is sent correctly - various tools can be used for this, like the chrome developer console's network tab to examine request parameters and payload. step3: Examine the values transmitted on the server side

Corrections: steps1 & step2: I tested your java script code - the request is being successfully sent. Only a minor adjustment is required in your code :

function signup() {
        var name = document.getElementById('name').value;
        var mobileNo = document.getElementById('mobileNo').value;
        var emailId = document.getElementById('emailId').value;
        var password = document.getElementById('password').value;
        var data = {
            "name" : name,
            "password" : password,
            "mobileNo" : mobileNo,
            "emailId" : emailId
        };
        var sendData = function(data) {
            alert("sending: " + JSON.stringify(data));
            $.ajax({
                url : 'http://localhost:8080/jsondem/pass',
                type : 'POST',
                contentType : 'application/json',
                data : JSON.stringify(data),
                success : function(response) {
                    alert(response);
                },
                error : function(response) {
                    alert('error' + JSON.stringify(response));
                }
            });
        };
        sendData(data);
    }

step3: Below is the code utilized to test via servlet

@WebServlet(urlPatterns={"/pass"},name="testServlet")
public class TestServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("received the request");
        BufferedReader br = req.getReader();
        String s = br.readLine();
        while(s!=null){
            System.out.println("line read is " + s);
            s = br.readLine();
        }
        br.close();
    }   
}

console output: line read is {"name":"a","password":"d","mobileNo":"b","emailId":"c"}

If you opt not to use servlets and wish to directly manage it using URLConnection, provide the stacktrace received.

Answer №3

When reconnecting to the server on the server side, ensure you have a solid grasp of the servlet model in Java. It's crucial to properly implement a servlet and understand how to extract parameters from client requests. Your client-side (javascript) implementation seems fine as it sends a correct request to

http://localhost:8080/jsondem/pass
with a JSON body (though a POST method would be more suitable). However, your server code contains errors:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    new JavaHttpUrlConnectionReader();

}

In the above snippet, you need to extract data from the request object.

String myUrl = "http://localhost:8080/jsondemo/pass";
  // If your URL may contain special characters, encoding is necessary:
  myUrl = URLEncoder.encode(myUrl, "UTF-8");

 doHttpUrlConnectionAction(myUrl);

}
catch (Exception e)
{
  System.out.println(e);
}

The snippet above shows an attempt to re-establish a connection from the server side to the server itself. This is likely not your intended action.

System.out.println("Name: " + name);

long mobileNo = (long) jsonObject.get("mobileNo");

System.out.println("Mobile Number: " + mobileNo);

String emailId = (String) jsonObject.get("emailId");
System.out.println("Email Id: " + emailId);


String password = (String) jsonObject.get("password");
System.out.println("Password: " + password);

If your goal is to send strings back to the client, note that System.out.println only logs messages to the server console. You should use the response object for sending data back to the client:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    new JavaHttpUrlConnectionReader();

}

Answer №4

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>pass</servlet-name>
        <servlet-class>pass</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>TestServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>pass1</servlet-name>
        <servlet-class>pass1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>pass</servlet-name>
        <url-pattern>/pass</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>pass1</servlet-name>
        <url-pattern>/pass1</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

click on this link @Balaji Krishnan

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

The element cannot be found in the DOM after it has been dragged and dropped

While using selenium webdriver, I encountered an issue when attempting to drag and drop a column of a table. The error message "Element is no longer attached to the DOM" appeared immediately after the dragging action. Below is the code snippet that I uti ...

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

Tips for verifying the information transmitted to a PHP website using JSON format

Upon clicking the "add to basket button" in OpenCart 3, I need to verify the data sent by JSON in the target PHP page. Is there a way to perform this verification in the PHP page using methods like print_r? Or perhaps there is a more effective approach? ...

The Mongoose save functionality is failing to work and is resulting in an empty {} object being returned

I've been working on constructing an Auth API with Mongo and Nodejs. The initial setup is complete, but I'm encountering an issue. When I make a request to the register API, it returns an empty object. Here's a snippet of my schema: con ...

Encountering a problem with GraphQL API fetching in Next.js: receiving the error message "React functionality 'useContext' is not supported in this environment."

Currently, I have developed a Next.js 14.2.3 application with a GraphQL API endpoint (which I replaced with localhost for StackOverflow). For data fetching, I am utilizing "@apollo/client": "^3.10.3" and "graphql": "^16.8.1". The product page path has been ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

What could be causing the PriorityQueue's values to shift after using the poll method in Java?

I have encountered an issue with the PriorityQueue in Java and could use some clarification. Specifically, I am confused about how the values "5" and "6" are being prioritized after the poll method is used in a PriorityQueue. This is a concept that I strug ...

The server is constantly sending data through Server Sent Events

I am currently a student working on a project involving a social trading platform. I am looking to incorporate a notification system and believe that SSE would be a great fit for this purpose. However, I am facing an issue where my SSE code is sending data ...

Images from JSON cannot be loaded in ReactJS

It seems that importing image URLs from a JSON file is not working as expected, resulting in certain issues. However, when importing them using the syntax {require("hardcoded URL")}, it works fine. But if variables are used as shown in the image below or l ...

Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu: nav { height: 40px; width: 100%; background: #F00; font-size: 11pt; font-family: Arial; font-weight: bold; position: relative; border-bottom: 2px solid # ...

Alter the content of a div depending on the values of three different elements

Hello everyone, I am new to the world of jQuery and javascript, and I am facing a challenge that I need some help with. Within a form, there are two fields that I would like to perform calculations on. Here is what I have attempted so far: jQuery.fn.calcu ...

The foundation of JSON and its structural encoding

Looking to deserialize JSON from Java, here's how it's done: Java jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO); JSON "accounts" : [ { "name" : "1009427721", "value" : 16850.79, "children" : ...

Add the JavaScript files to the components

I am working on integrating an admin template into my Angular2 project (version 2.1.0) which is already equipped with Bootstrap, jQuery, and jQuery plugins. Since there are numerous jQuery plugins and JS files involved, I am faced with the challenge of ho ...

N8N: Deleting JSON Key from Output

Is it possible to remove the json key in my output file? I am unsure of the best approach to achieve this. I would like to return an array of data with all values, not just one value. If you want more information, here is a link to my N8N post: Manipulate ...

What is the necessity of utilizing getStaticPaths() alongside getStaticProps()?

When working with dynamic routes, such as [id].js, the static pages generated using npm run build will result in an [id].html page. Any route containing /something will display "Hello World". However, when we dynamically generate content on the page by ut ...

Troubleshooting: PHP AJAX Image Upload Issue - Images Not Being Uploaded

I am having an issue with my code. Although it doesn't show any errors in the console, clicking the upload button does not trigger any action. Following a tutorial, I tried to send a post request to itself, but the image is neither uploaded to the des ...

Transform charset X to Unicode using Java

What is the process to convert a specific charset to unicode in Java? We have discussed charsets extensively, but this particular topic has not been covered yet. I have a hex string that follows the criteria length%4==0 (e.g. \ud3faef8e). Typically, ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Issues arise when Angular Meteor fails to load the UI-Router properly

Currently, I am exploring the integration of ui-router for routing within a meteor-angular application. My reference point is the meteor Whatsapp tutorial which can be found here Below is the relevant code snippet related to ui-router implementation: log ...

JavaScript: set values to elements in an array

Below is the code snippet I am working with: function gotData(data){ result = data.val() const urls_kws = Object.keys(result) .filter(key => result[key].last_res > 10) var keywords = urls_kws; c ...