Parse the JSON in spring? - java

I know it is a simple question .But I can't find a answer.
How to parse this Jquery ajax.
My Jquery ajax success response will be,
{"status" : "ready"};
Help me to do this.

My Jquery ajax success response will be,
From the above line , I assume you are looking to parse the JSON response in the client side. In javascript you can parse it as :
var json = '{"status" : "ready"};',
var obj = JSON.parse(json);
In Java , using GSON :
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(yourJsonString);
JsonObject jsonObject = element.getAsJsonObject();

Related

Forming custom JSON Object from the JSON response from elastic search

Am getting response from ElasticSearch, from that response i want to form another JSON with limited fields (like custom JSONObject).
Please find the response that am getting from elastic search.
{
"took":93,
"timed_out":false,
"_shards":{
"total":5,
"successful":5,
"skipped":0,
"failed":0
},
"hits":{
"total":1,
"max_score":1.0,
"hits":[
{
"_index":"attachment",
"_type":"doc",
"_id":"87740",
"_score":1.0,
"_source":{
"app_language":"ES",
"filetype":"PB",
"attachment":{
"date":"2006-05-03T15:17:53Z",
"content_type":"application/pdf",
"author":"JJamesN",
"language":"en",
"title":"Microsoft Word - te7000pb.doc",
"content":"European Electronic Controls Catalog ",
"content_length":12267
},
"ext":"pdf",
"fileContent":"JVBERi0xLjQNJeLjz9MNCjQ3ID"
}
}
]
}
}
Please find my java code that am trying to manipulate the response JSON to create a separate JSON with limited fields.
JSONObject jsonObject = new JSONObject(responseBody);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray hitsArray=hits.getJSONArray("hits");
System.out.println("Hits---->"+hitsArray.toString());
From the response JSON, i just want to create a new JSON with the following Structure and fields.
{
"app_language":"ES",
"filetype":"PB",
"attachment.content" : "European Electronic Controls Catalog ",
"ext":"pdf",
}
Try this:
JSONObject jsonBody = new JSONObject();
jsonBody.put("app_language","value");
jsonBody.put("filetype","value");
jsonBody.put("attachment.content","value");
jsonBody.put("ext",ext);
//String requestBody = jsonBody.toString();
Just extract your values from response and use it any where you want.
Hope this helps.

RestAssured JsonPath to String

Is there a way to convert the whole JSON path data to a string in Java?
I am working on APIs and their responses are in JSON format. It is easy to understand the JSON structure through Postman/WireShark but I am trying to run an API request through Java, grab the response, convert the raw response to JSON, convert JSON response to a string format and print it. The method '.getString()' is to access a particular element and not the whole data. The method '.toString()' does not work on JSON data either.
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String id = json.get("id");
log.info("The id is " + id);
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = ???;
log.info("The complete json data is " + complete_json_data);
The code snippet which is mentioned "???" is what I was trying to achieve.
The methods which can convert a JsonPath object into a String are:
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettify();
and
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettyPrint();
var obj = { "field1":"foo", "age":55, "city":"Honolulu"};
var myJSON = JSON.stringify(obj);

Remove back slash from Json String in android

i need some help for Remove Back slash from Json String.
Here is the Response which i Get From Server side.
"response":"{\"time_zone\":\"\",\"session_token\":\"abcdefgHijklomopqrstuvwxyz\",\"user_login\":\"abc\",\"user_profile_img\":\"http://jhjhjhj.org/system/photos/62/medium/images.jpg?1462446436\",\"success\":\"0\",\"org_admin\":\"\",\"user_id\":\"62\",\"user_org_id\":\"101\",\"phone_mobile\":\"510-427-9639\",\"user_email\":\"abc#pdmoffice.com\"}"}
what i have don for Remove Backslash from this String
result.replaceAll("\\","");
than After it will give me This String which is not in Json Formate.
{"response":"{"time_zone":"","session_token":"nskfndkjfsfsdffjsdfd","user_login":"newoff2","user_profile_img":"http://absdds.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9639","user_email":"hjhjh#pdmoffice.com"}"}
it Give me Exaption
org.json.JSONException: Unterminated object at character 17 of
{"response":"{"time_zone":"","session_token":"kjshhdscncnxzcxclx","user_login":"newoff2","user_profile_img":"http://abcd.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9898","user_email":"sdgas#pdmoffice.com"}"}
How Can i remove this Back slash with Proper Json Formate ?
Thanks in advance
The command
result.replaceAll("\\","");
is correct and if you try to display the server response with an online json formatter (https://jsonformatter.curiousconcept.com/) you can clearly see that the string is not correctly formatted. The double quotes after the "response" and one at the end are not required.
UPDATED: August 2019
Use google's Gson for parsing to Json by omitting backslash automatically:
JAVA CODE:
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse("your jsonString with backslash").getAsJsonObject();
KOTLIN CODE:
val jsonParser = JsonParser()
val jsonObject = jsonParser.parse("your jsonString with backslash").asJsonObject
An alternative to remove backslashes from JSON string.
s = Your String with Back Slash
For converting String to JSONObject:
JSONObject jsonObject = new JSONObject(s);
For converting String to JSONArray:
JSONArray jsonArray = new JSONArray(s);
You can try this and it will work fine
String jsonStr4 = jsonStr3.replaceAll("\"", "");

Rest Assured: java.lang.AssertionError: JSON path body doesn't match

The following is the JSON response I get when I hit a url:
{"status":"success","body":[{"id":1,"name":"ALL"},{"id":2,"name":"VW_CMPNY"},{"id":3,"name":"EDT_CMPNY"},{"id":4,"name":"ADD_CMPNY"},{"id":5,"name":"DLT_CMPNY"},{"id":6,"name":"VW_GRP"},{"id":7,"name":"EDT_GRP"},{"id":8,"name":"ADD_GRP"},{"id":9,"name":"DLT_GRP"},{"id":10,"name":"VW_ACCNT"},{"id":11,"name":"EDT_ACCNT"},{"id":12,"name":"ADD_ACCNT"},{"id":13,"name":"DLT_ACCNT"},{"id":14,"name":"VW_INVC"},{"id":15,"name":"EDT_INVC"},{"id":16,"name":"ADD_INVC"},{"id":17,"name":"DLT_INVC"},{"id":18,"name":"ON_RCRD"},{"id":19,"name":"OFF_RCRD"}]}
I'm checking that the JSON response is equal to a .json file I have; this is my code:
URI permissionsUri = new URI(permissionsUrl);
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(new FileReader("\\db\\seed\\permission.json));
JSONArray expectedJson = (JSONArray) obj;
String expectedStatus = "success";
get(permissionsUri).then().assertThat().body("status", equalTo(expectedStatus)).and().body("body", equalTo(expectedJson));
But I'm getting the following error:
java.lang.AssertionError: JSON path body doesn't match.
Expected: <[{"id":1,"name":"ALL"},{"id":2,"name":"VW_CMPNY"},{"id":3,"name":"EDT_CMPNY"},{"id":4,"name":"ADD_CMPNY"},{"id":5,"name":"DLT_CMPNY"},{"id":6,"name":"VW_GRP"},{"id":7,"name":"EDT_GRP"},{"id":8,"name":"ADD_GRP"},{"id":9,"name":"DLT_GRP"},{"id":10,"name":"VW_ACCNT"},{"id":11,"name":"EDT_ACCNT"},{"id":12,"name":"ADD_ACCNT"},{"id":13,"name":"DLT_ACCNT"},{"id":14,"name":"VW_INVC"},{"id":15,"name":"EDT_INVC"},{"id":16,"name":"ADD_INVC"},{"id":17,"name":"DLT_INVC"},{"id":18,"name":"ON_RCRD"},{"id":19,"name":"OFF_RCRD"}]>
Actual: [{id=1, name=ALL}, {id=2, name=VW_CMPNY}, {id=3, name=EDT_CMPNY}, {id=4, name=ADD_CMPNY}, {id=5, name=DLT_CMPNY}, {id=6, name=VW_GRP}, {id=7, name=EDT_GRP}, {id=8, name=ADD_GRP}, {id=9, name=DLT_GRP}, {id=10, name=VW_ACCNT}, {id=11, name=EDT_ACCNT}, {id=12, name=ADD_ACCNT}, {id=13, name=DLT_ACCNT}, {id=14, name=VW_INVC}, {id=15, name=EDT_INVC}, {id=16, name=ADD_INVC}, {id=17, name=DLT_INVC}, {id=18, name=ON_RCRD}, {id=19, name=OFF_RCRD}]
I don't know why I'm getting the = in place of :. How can I solve this?
When I need to compare response value with restAssurd, I do the following and it works:
Response response = given()
.given().header("Content-Language", "en_US")
.contentType("application/json")
.body(ApiBody)
.when()
.post(baseApiUrl);
JsonPath jp = new JsonPath(response.asString());
log.info(response.asString());
String value = jp.get("valueToCheck").toString();
Assert.assertEquals(valueToCheckFromResponseJson, actualValue, "Value from API doesn't match Value from DB");
The "actual" part looks like the toString call on a collection or an array. You are comparing the contents of the JSONArray class against an actual JSON document. You have to serialize the JSONArray as a JSON document before comparing it against the response of your service.

How to consume/deserialize .Net WCF service JSON response in Java

I am having problem while consuming/deserializing WCF .NET JSON response in Java. JSON response is in the following format.
{"d":"[
{\"ID\":123,\"Company\":\"Microsoft\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.microsoft.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"},
{\"ID\":124,\"Company\":\"Google\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.google.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"},
{\"ID\":125,\"Company\":\"Apple\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.abc.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"}
]"}
While on the Java code side I am having problem to deserialize this json response to get out my objects and their corresponding properties.
This is the java code currently I am using to deserialize json response.
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
if (element.isJsonObject()) {
JsonArray companies = element.getAsJsonArray();
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}
Is there any problem in the JSON response format or its right? any kind of help is appreciated, thanks in advance.
I'm not sure why you're getting that response - it't not valid json. There are two things wrong with it
The outer square brackets should not be wrapped in quotes.
The quote escape characters need to be removed (not sure if this is just you putting them in?)
Without you posting the actual error you get (hint: even though stack overflow is powerful, we have not yet developed the ability to read minds) it's very difficult to know what the actual problem is.
Tom is right. Valid JSON should look like this:
{"d":[
{"ID":123,"Company":"Microsoft","Country":"USA",
"website":"http://www.microsoft.com",
"FirstName":"john","Email":"abc#gmail.com"},
{"ID":124,"Company":"Google","Country":"USA",
"website":"http://www.google.com",
"FirstName":"john","Email":"abc#gmail.com"},
{"ID":125,"Company":"Apple","Country":"USA",
"website":"http://www.aabc.com",
"FirstName":"john","Email":"abc#gmail.com"}
]}
And your code like this:
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
JsonObject object = element.getAsJsonObject();
if (object.isJsonObject()) {
JsonArray companies = object.getAsJsonArray("d");
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}

Categories

Resources