Format JSON String in JSP - json

I have started working on JSON, I am returning a JSON from JSP through AJAX call. Its working well.
only i need to change the format of my returning JSON String.
Following is the String what my JSP is returing.
[{"VV":0,"desc":"XXXXXXX","amount":0,"date":"12/03/2013","watch":""},{"VV":1,"desc":"XXXXXXX","amount":1,"date":"12/03/2013","watch":""}]
and Below is the String what I want my JSP to return.
{"total":"2","rows":[{"VV":0,"desc":"XXXXXXX","amount":0,"date":"12/03/2013","watch":""},{"VV":1,"desc":"XXXXXXX","amount":1,"date":"12/03/2013","watch":""}] }
Can Any one please help.
Following code I am using to send the output back to front end.
JSONArray arrayObj=new JSONArray();
JSONObject json = new JSONObject();
json.put("VV", i);
json.put("desc", "XXXXXXXXX");
json.put("amount", 1);
json.put("date", "12/03/2013");
json.put("watch", "");
PrintWriter out1 = response.getWriter();
out1.println(arrayObj);

What you need to so with the "json" object that you have created is to allocate to a new variable. Something like this:
arrayObj.put(json);
Next you need to create another object:
JSONObject finalObj = new JSONObject();
finalObj.put("total", 2);
finalObj.put("rows",arrayObj);
finalObj.flush();

I think you need to convert it to String and override the toString() method according to your needs and pass it to your JSP page

Related

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));

Servlet doesnt write JSON Output to AJAX

Following code for my output:
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
ToJson obj = new ToJson();
String obj1 = objectMapper.writeValueAsString(obj);
response.setContentType("application/json");
out.print(obj1);
System.out.println(obj1);
out.close();
The obj1 looks like this: {"prname1":"P1neu","anz1":"342356","prid1":"1","price1":"25"}
It should send the string out so I can parse it in my AJAX and display it but somwhow it ends up with nothing as console.log/etc doesnt display any data.
I had out.append but it also didnt work.
Use below code to send response as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(obj1);
Please check this How to use Servlets and Ajax?
It will surely help you.

Use a JSON with JSONOBJECT in Java

I want to use the following JSON in my code in Java:
[
{
"speed": 200
}
]
I tried to write this line :
JSONObject jsonBody = new JSONObject("[{\"speed\": 200}]");
But I always get an error. What is the exact format that I have to use here??
EDIT: So it would be more proper to use a JSONArray rather than use a JSONObject (as my last post said)
So the correct java code would be
String json = "[{\"speed\": 200}]";
System.out.println(json);
JSONArray jsonBody = new JSONArray(json);
System.out.println(jsonBody.getJSONObject(0).get("speed"));

RestSharp: get JSON string after deserialization?

using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for

JSON, Servlet, JSP

Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
Can I pass the parameters from the database?
Once the URL is entered, the information returned will be in text format using JSON
format.
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
How shall I do this in servlets? doPost()
Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)
Jackson is another option for JSON object marshalling.