简体   繁体   中英

Simple JSON-String Query

I am developing a web-app using AJAX requests on the client-side and Servlets on the server-side.

My aim is to send objects of Javascript to server, then do some manipulations there and send it back to show here.

Let's say my js object is

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

My Approach

1.Convert obj to JSON string and send

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

2. Recieve string,convert this back to JSON, manipulate "name" to "Bruce Wayne" and send it back as string

3.Recieve and convert back to Json

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

I am struggling at second point.I am using org.json for it .I searched and read docs but could not find satisfied answer for converting string to json and vica-versa in JAVA in my context.

It would be really helpful one could provide simple working code or point to some links where I can study.

PS :

I cannot use Jquery as I am using AngularJS. See Why?

I will always send valid JSON string.

I can use other JSON lib. if its good than org.json and satisfy my needs. Please provide its jar download link.

Assuming you are able to pull out data in your server code

This is how you can do it using org.json :

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

Code to create the response can look something like this:

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

This assumes your server method returns a String type

And in case if you are using Servlet you can use HttpServletResponse object res to create response like:
res.setContentType("application/json"); OutputStream os = res.getOutputStream(); os.write(response.toString().getBytes()); os.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM