Transform a JSON string in JavaScript into a Java object

Is it possible to convert a JavaScript JSON string into a Java object in a Java web application? I converted an ArrayList to a JSON string and sent it to a JSP page. Now, on the JSP page, I want to iterate through the JSON string. Is there a way to do this without converting it back to a Java object?

For example, how can I use the name from the JSON string to populate an input text box field?

[{"name":"john"}, {"lastname":"nice"}];

And then set the value in the input text field:

$("#textbox").val("namehere");

Is this achievable?

Here is my current process:

I have a button that triggers an AJAX call, and in the servlet, I convert an ArrayList to JSON.

ArrayList<UserProfile> users = new ArrayList<UserProfile>();

The UserProfile class consists of name, last name, and email fields.

users.add(new UserProfile("john", "garcia", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117b7e797f517062753f727e7c">[email protected]</a>"));
users.add(new UserProfile("cena", "brock", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c1d1ccc0c8c0c6cdcce3c2d0c78dc0ccce">[email protected]</a>"));

Then, I return this data to the JSP page.

out.println(gson.toJson(users));

When receiving the data in the AJAX success function:

success: function(data) {
    // I want to access every element of the ArrayList parsed to a JSON string
}

Answer №1

If you understand the request, you can implement the code like this.

However, if your output is an array of Java objects, using a form will not work. Instead, you should use a table or list to display all the data, as the form will only show the last item in the array.

It's important to note that this is not Java object, but rather JSON iteration.

<form>
    <input type="text" id="name" name="name" />
    <input type="text" id="lastname" name="lastname" />
</form>

<script type="text/javascript">
    //your code

    success:function(data){
        for(i in data)
            $("#" + i).val(data[i]);
    }
</script>

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

Which characters are permissible for the id attribute to prevent the jQuery selector from throwing an exception?

I am facing a situation where the id attribute is inputted by an end user. For instance, if the id for a textbox is "11_=11" as entered by the user, then the HTML code will appear like this: <input type="text" id="11_=11"> The corresponding jQuery ...

Sending a String input to a Custom Deserializer with Jackson Library in Java

I recently developed a custom deserializer using Jackson to handle the deserialization of a JSON string: public class CustomDeserializer extends StdDeserializer<CustomObject> { public CustomDeserializer() { this(null); } public ...

Are Global variables supported in the EXT JS framework?

When working with Java and C++, it is common practice to store a variable globally so that its value can be accessed from anywhere within the project. For example, if I am working inside a class named Residence and saving an INT as the residenceNumber to a ...

Adjusting the field of view of a perspective camera in THREE.JS while maintaining the camera's original distance

My ultimate goal is to adjust the FOV value of my camera while triggering an animation. However, upon implementing the FOV value changes, I notice that my scene appears smaller. This has led me to question the mathematical relationship between the FOV val ...

Nesting divs that soar within a contained div (not spanning the entire page)

I need the div elements to move within another div container instead of flying over the entire page. What changes do I need to make in the code to achieve this? $(document).ready(function() { $('.balloon').each(animateDiv); }); function ma ...

methods for extracting data from nested JSON arrays in Android

Can anyone assist me in fetching the URL from the JSON array thumbnail_images? The URL I need is nested inside another array called medium_large. I have successfully retrieved the URL from the following JSON: "attachments": [ { "id": 367, "url": ...

The simulated function is not being invoked while inside an asynchronous function

Summary: I encountered issues with my tests after making some code changes. I recently added asynchronous conditional checks to some existing code, resulting in my tests failing unexpectedly. The tests were set up to ensure that a mock function passed as ...

What are the steps for programmatically executing queries in MongoDB?

I want to be able to generate code like this: var result = Attributes.find({ attribute_name : { $exist : true, $in : [1] } }); However, when I tried to create it programmatically, I ended up writing code like this: var genQuery = '{ "& ...

Facing difficulties with the XPATH due to an inability to access specific parts of the HTML code

Currently, I am facing an issue where I need to click on a link using Selenium and Java. When searching for the link using XPath, I am encountering a problem where only white spaces are displayed instead of most of the webpage content. The highlighted link ...

Ways to prevent scrolling or switching to the next tab when my javascript function yields a false result

//HTML Code <div id="navigation1"> <ul> <li><a href="#"><input type="submit" value="Next" onClick="return checkfhname()" /></a></li> </ul> </div> Whenever my Javascript function checkfhname() r ...

Steps to store a string with all characters in a JavaScript variable

I am faced with a situation where I need to pass variables that are considered Javascript objects, in a format similar to the following: var pageVars= [ { origin:'page', property:'name', value:'whatever' }, { origin:& ...

Ways to make .addAction carry out a specific task

I have a question that might have been asked previously, but I am still uncertain about what to do. As a newcomer to Android Studio and app development in general, all the terms seem unfamiliar to me. When I click snooze or stop on my app, I'm not sur ...

Decoding JSON files using Golang

Looking for a way to access the value of sha in a JSON structure using Golang? { "some text":[ { "sha":"1234567", "message":"hello world", "author":"varung", "timestamp":1479445228 } ] } Can you help me figure out the best a ...

What are the steps to create a custom progress bar using JavaScript?

I have experience with HTML and CSS. Below is the HTML code: <div id="wrapper"> <ul id="top"> <center><li><a href="#one" class="button">GENERATE</a></li></center> </ul> <div class="box" i ...

Is there a way to secure a BufferedImage with encryption so that it can only be accessed by the program itself

Within the Buffers class, I have the following method: private static BufferedImage load(String s){ BufferedImage image; try{ image = ImageIO.read(Buffers.class.getResourceAsStream(s)); return image; ...

Determine the following workday using a PowerShell JSON loop

Discovering a convenient JSON API from Kayaposoft that provides a true/false response for whether a specified day is a work day or not (e.g. Sunday the 14th of April; isWorkDay: false). This API even recognizes local holidays like Vappu in Finland. As I a ...

What is the best way to retrieve the value from a textarea and verify if it is blank or not?

I have successfully incorporated a textarea using simpleMde, but I am facing difficulty in retrieving the value and checking whether it is empty or not. var message = document.getElementById("simpleMde").value; console.log(message); <textarea class=" ...

"Discover the power of D3.JS with three dazzling charts on a single page, plus a host of additional

As a student, I struggle with English and it makes me feel sorry and anxious... Despite that, I want to create three scatter plot charts on the same page using a single data file (csv). The dataset includes columns for Name, Height, Weight, and Grade (ra ...

Generate a unique identifier and verify its presence within an array of objects

Is there a way to generate a unique identifier and add it to an object in an array, only if the id does not already exist in any other objects within the array? Within the React code snippet provided below, the "saveColor" function was intended to accompl ...

What is the most effective way to use Javascript to update an image depending on the selected value in a dropdown

My JavaScript skills are limited, but I have successfully created a form with 4 drop-down selection boxes on the left side for users to choose from (State, Car, Year, Condition). After making their selections, users can click a 'calculate' butto ...