Querying JSON strings the easy way

Currently, I am in the process of developing a web application that utilizes AJAX requests on the client-side and Servlets on the server-side.

The main goal is to send JavaScript objects to the server, perform manipulations there, and then return them to display on the client-side.

Let's assume my JavaScript object looks like this:

var obj={hero:"Spiderman",name:"Peter Parker"};

This is how I plan to approach it:

1. Convert the object to a JSON string and send it:

var str= JSON.stringify(obj);
xmlhttp.open("POST",myurl,true);
xmlhttp.setRequestHeader("Content-Type","application/json",true);
xmlhttp.send("data="+str); 

2. Receive the string, convert it back to JSON, change the "name" value to "Bruce Wayne," and send it back as a string.

3. Receive and convert back to JSON:

var data= JSON.parse(xmlhttp.responseText);

I am currently facing difficulties at the second point. I have tried using org.json for this purpose but have not found a satisfactory solution for converting strings to JSON and vice versa in Java within my specific context.

If possible, could someone provide some simple working code or direct me to resources where I can further study this issue?

Also, please note that I cannot use jQuery due to my utilization of AngularJS. You can read more about it here.

Rest assured, I will always be sending valid JSON strings.

If there is an alternative JSON library that you recommend over org.json and that meets my requirements, please provide a link to download its JAR file.

Answer №1

If you have the ability to retrieve data in your server-side code

Here is an example of how you can achieve this using org.json:

JSONParser parser = new JSONParser();
JSONObject requestObj = (JSONObject) parser.parse(data);
String name = (string)requestObj.get("name");
name = "Bruce Wayne";

The code for generating the response may look something like this:

JSONObject response = new JSONObject();
response.put("name",name);
return response.toJSONString();

This assumes that your server method returns a type of String

If you are utilizing Servlet, you can use the HttpServletResponse object res to generate the response as follows:

res.setContentType("application/json");
OutputStream os = res.getOutputStream();
os.write(response.toString().getBytes());
os.close();

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

Retrieving a particular object/item based on its id using Firebase

Currently in the process of developing a small web app using Firebase and React, I am encountering difficulty retrieving specific items from Firebase on the client-side of React. In traditional JavaScript, a basic fetch request might appear as follows: ...

React is unable to assign a class field beyond the scope of axios

class App extends React.Component { app: Application; ... componentDidMound() { axios.get(…).then(res => { this.app.currentUser = res.data.data; // setting value inside lambda function. console.log(this.app.currentUser); // ...

Redirecting in AngularJS after a successful login操作

Is there a way to redirect users back to the original page after they login? For example, if a user is on a post like www.example.com/post/435 and needs to log in to "like/comment" on the post, how can I automatically redirect them back to that specific po ...

Displaying a div when hovering over it, and keeping it visible until clicked

I want to display a div when hovering over a button. The shown div should be clickable and persistent even if I move the cursor from the button into the shown div. However, it should be hidden when moving out of the entire area. I'm unsure about how ...

Error encountered in Laravel 5.2 AJAX request due to a Token Mismatch Exception

I keep receiving a token mismatch exception even though everything seems correct to me. Here is the code from my view: @extends('layouts.master') @section('content') <div class="bg"></div> <div class="login-sec clearfix ...

Increase the state by 1 every interval, unless the current state is equal to or greater than the maximum value by using

How can I create an animation effect by incrementing the current state by 1 until it matches a specified maxValue? The interval for this animation is set using setInterval, but I want it to stop when the state reaches the maximum value. Currently, when th ...

Upon successful authentication, the WebAuthenticationBroker.authenticateAndContinue function does not activate the app

I'm attempting to implement Facebook, Twitter, and Google login using WebAuthenticationBroker.authenticateAndContinue. The authentication page is displayed successfully, but once the authentication is complete, the activated event is not triggered and ...

"Looking to incorporate web vitals metrics into the footer of my webpage using Next.js and React hooks - any suggestions on how to

I'm new to next.js and react and recently discovered that next.js has a built-in feature for logging performance metrics like FCP. I would like to incorporate this into my Metric component. You can find more information about measuring performance on ...

Attempting to access the 'name' field from an input element in an HTML document using AngularJS, and also introducing a static field named 'likes' with a value

Currently, I am in the process of developing an application that retrieves a list of Beers from an API. Each beer in the JSON response contains the fields {name: "beer", id: number, likes: number}. However, I am facing a challenge while attempting to add ...

Show the current Date and Time dynamically using only one line of JavaScript code

After running this command, I encountered an issue: $("#dateTime").text(new Date().toLocaleString()); The result displayed was 2/21/2020, 10:29:14 AM To make the time increase every second, I attempted this code: setInterval($("#dateTime").text(new Dat ...

Java displays Russian characters as "???"

I'm facing an issue with my controller where I need to return a JSON string containing a Russian name, but all I'm getting in response are question marks (invalid characters). @Controller public class ManifestController { @ResponseBody ...

Combine two entities to create a new entity that mirrors the structure of the first entity

Can someone assist me with a data structure issue? Here are the objects I am working with: const elements = { item1: {color: 'blue', name: 'Item One' }, item2: {color: 'green', name: 'Item Two' }, item3: {colo ...

Exploring deeper into JSON data structures

I've been trying to figure out how to access nested data in a JSON document using jQuery, but I'm having trouble grasping the concept. I am still new to jQuery and JSON, so any help would be greatly appreciated. The specific data I need is the Su ...

What is the best way to sort through data retrieved by a server component in a NextJS 13 AppDir?

I've hit a roadblock trying to integrate a search bar that filters server-fetched data in my project using NextJS 13 and AppDir. Despite numerous attempts, I can't seem to get it right. It feels like there's something crucial I'm overlo ...

Issue with Loading Data on AJAX Causing Scrolling Difficulties

Currently, I am in the midst of website development using PHP, MySQL, and JavaScript (JQuery + Ajax). One issue that has arisen is with the customer scroll function and scrollbars. When loading data via ajax, the scroll function is generating numerous erro ...

How can you conceal the navigation and footer components on a 404 page using Next.js?

import Footer from "./Footer"; import Navigation from "./Navigation"; import { useRouter } from "next/router"; function CustomLayout({ children }) { const router = useRouter(); return ( <> {router.pathname ...

Android webview encounters issues with loading javascript and css files

I am facing an issue with my Angular web app that I want to run locally inside a WebView of my android app. However, upon opening the app, all I see is a blank screen. Upon inspecting the chrome tool, I noticed a net::ERR_FILE_NOT_FOUND error for the .js ...

Escaping messages in json format with slf4j and log4j2

Currently, I am utilizing slf4j and log4j2 for logging implementation. My goal is to have my JSON messages logged as JSON itself rather than being escaped as Strings. Upon examining the org.apache.logging.log4j.layout.template.json.resolver.MessageResolve ...

Issue: A file that has been uploaded completely ignores the req.on() method in NodeJS

I am currently using MEAN.IO to create a web application. Right now, I am working on implementing an image uploader feature. I have decided to use angular-file-upload for this purpose, and it seems to be functioning well. However, I am facing an issue on ...

Verifying the size of the unordered list and deleting a list item

I'm attempting to remove the last <li> element from a <ul> element only if it goes beyond a certain length. To achieve this, I have implemented the following code: var selector = "#ulelement" if($(selector).children().length > threshol ...