I am working on a jersey - java project where I have to get the json data in string format and parse each data separately. I am able to get the response in string using post method. When I try to use JSON lib to parse the string data class not found exception is produced. I want the returned string to be split up. Below is my json.
{
"startdate": "11/11/11",
"enddate": "12/12/12",
"operation_name": "task1",
"user_id": "user1",
"operation_key": ["KKMM-025", "SFF-025", "TTR-022"]
}
Resource method
#POST
#Path("OpertaionDetails")
#Consumes({MediaType.APPLICATION_JSON , MediaType.APPLICATION_XML})
public Response CreateOperations(String incoming_data) throws Exception
{
try
{
JSONParser parse = new JSONParser(); // class not found exceptin i have added the lib properly its working fine when it is used in main method of java.
JSONObject jobj = (JSONObject)parse.parse(incoming_data);
JSONObject Jstart_date = (JSONObject) jobj.get("startdate");
// this data to be paresed
System.out.print("incomingData"+incoming_data);
}
catch(Exception e)
{
e.printStackTrace();
}
return Response.ok(incoming_data).build();
}
Related
I am developing an API , where I receive some article related data as a POST request. The receiver I have as following:
#ApiOperation(value = "Add a new Article", produces = "application/json")
#RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity createPost(#RequestBody String postContent) {
try {
// Here I need to conver the postContent to a POJO
return new ResponseEntity("Post created successfully", HttpStatus.OK);
} catch (Exception e) {
logger.error(e);
return responseHandler.generateErrorResponseJSON(e.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Now it works for simple request like:
{
"id": "1",
"title": "This is the Post Title",
"body": "This is the Post Body",
"authorName": "Test",
"tagList": [
"tag-1",
"tag-2",
"tag-3"
]
}
But in real scenario I will get receive a HTML content as the value of the "body" key in request JSON, which can have "",<,> or many thing. Then the String to JSON conversion will fail. Is there any api, library or example, where I can have HTML content as the value of a JSON key.
Following is my input request where the code is failing to parse the JSON to Object:
{
"menuId": "1",
"title": "This is the Post Title",
"body": "<p style="text-align:justify"><span style="font-size:16px"><strong>Mediator pattern</strong> is a Behavioral Design pattern. It is used to handle complex communications between related Objects, helping by decoupling those objects.</span></p>",
"authorName": "Arpan Das",
"tagList": [
"Core Java",
"Database",
"Collection"
]
}
Now How I am parsing the json is like:
public Post parsePost(String content) {
Post post = new Post();
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(content);
post.setMenuId((Integer) jsonObject.get(Constant.MENU_ID));
post.setTitle((String) jsonObject.get("title"));
post.setBody((String) jsonObject.get("body"));
post.setAuthorName((String) jsonObject.get("authorName"));
post.setAuthorId((Integer) jsonObject.get("authorId"));
post.setTagList((List) jsonObject.get("tag"));
} catch (ParseException e) {
e.printStackTrace();
}
return post;
}
It is giving a parse exception :
Unexpected character (t) at position 77.
The library I am using for parsing the JSON is:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
I am currently working on a project where i need to make a rest call to an external API and parse the JSON response to a POJO and return back the POJO as JSON for another rest request. I am able to parse the JSON response, but my requirement is to parse only one particular node from it. How can i achieve this? I am using Spring Boot and Spring Rest Template to make the external rest call. Please help!!!
#RestController
public class ProductsController {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductsController.class);
#RequestMapping(value = "/myRetail/product/{id}", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE })
#ResponseBody
public Item getSchedule(#Valid Payload payload) {
String URL = "<External API>";
LOGGER.info("payload:{}", payload);
Item response = new Item();
RestTemplate restTemplate = new RestTemplate();
Item item = restTemplate.getForObject(URL, Item.class);
LOGGER.info("Response:{}", item.toString());
return response;
}
}
JSONResponse (This is a part of whole i receive)
{
"ParentNode": {
"childNode": {
"att": "13860428",
"subchildNode 1": {
"att1": false,
"att2": false,
"att3": true,
"att4": false
},
"att4": "058-34-0436",
"att5": "025192110306",
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
},
............
}
Required JSONpart from the above whole response:
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
}
Use the org.json library. With this library you can parse the payload to a JSONObject and navigate to your required subpart of the document.
So you have to get the payload as a JSON-String and parse it to the JSONObject from the library. After that you can navigate to your required subpart of the document and extract the value and then parse it to your required Java POJO.
Have look at: How to parse JSON
Just map the path to the needed object:
{
"ParentNode": {
"childNode": {
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
}
}
}
And then simply:
Response responseObject= new Gson().fromJson(json, Response.class);
SubChildNode2 att6 = responseObject.getParentNode().getChildNode().getSubChildNode2();
I am writing automation script to validate json responses of REST APIs and i am using faster xml to serialize and convert java object to json format.
I have a user case where I have to get the json response and add a new array element to an existing array and post it back.
The json response after GET looks like this :
{
"name":"test",
"id":"1234",
"nodes":[
{
"nodeId":"node1"
},
{
"nodeId":"node2"
}
]
}
To this json response, I need to add a third entry for nodes array
{ "nodeId": "node3" } and then post this.
Can someone please help me understand how to add a new array element to an existing array?
You can try:
//Your JSON response will be in this format
String response = "{ \"name\":\"test\", \"id\":\"1234\", \"nodes\":[ { \"nodeId\":\"node1\" }, { \"nodeId\":\"node2\" } ] }";
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray nodesArray = jsonResponse.getJSONArray("nodes");
JSONObject newEntry = new JSONObject();
newEntry.put("nodeId","node3");
nodesArray.put(newEntry);
jsonResponse.put("nodes",nodesArray);
} catch (JSONException e) {
e.printStackTrace();
}
Now you can post your jsonResponse.toString() as required.
I would rather go for cleaner approach, create Object with below structure -
public class Response{
private String name;
private int id;
private List<Node> nodes;
<Getter & Setter>
}
public class Node{
private String nodeId;
}
Serialize the json -
Response response = objectMapper.readValue(responseJson,
Response.class);
Add the new incoming node object to response -
response.getNodes().add(New Node("{new node Value}"));
Deserialize before post -
objectMapper.writeValueAsString(response);
I have a cloud endpoint function that returns a json string as response. An api endpoint makes an http request to the cloud function. How can I return the json string response as it is. I tried the following(just as an example)
#ApiMethod(
name = "json",
httpMethod = ApiMethod.HttpMethod.GET
)
public JsonObject json()
{
String item = "{\"name\":\"Josh\",\"sex\":\"male\"}";
JsonParser jsonParser = new JsonParser();
return jsonParser.parse(item).getAsJsonObject();
}
and I get the following message
WARNING: exception occurred while invoking backend method
[INFO] GCLOUD: java.io.IOException: com.fasterxml.jackson.databind.JsonMappingException: JsonObject (through reference chain: endpoints.repackaged.com.google.gson.JsonObject["asInt"]
Caused by: java.lang.UnsupportedOperationException: JsonObject
I understand JSONObject is not part of the supported returned type, I just want to know how I can just output the json string response from the endpoint just as it is
What you can do is to wrap your JSON into a String (in your endpoint) and return the wrapper object. You wrapper object could be a simple POJO with only one String attribute. Then on your API consumer side, you just read the string (representing your JSON) and use it as you wish.
According to : PlayFramework Document 2.0 & PlayFramework Document 2.1
I know that in play I can return:
Ok()
badRequest()
created()
status()
forbidden()
internalServerError()
TODO
etc...
I would like to send with ajax an response with my information in it. Unfortunatelly play sends only status information, and some kind of object which I do not understand.
Only method ok("Test message") sends status and my message information. Rest of it dosnt work.
How to deal with it?
-- Edit --
I have ajax method:
$.post($("#assignmentsubmitAddress").text(), { 'units' : submittedUnits },
function(response, status, xhr) {
showNotyfication(status, response);
})
When I return ok("test");
In java script variable response I have just String test
When I return badRequest("test"); In java script variable response I have java object. When I print variable response I am getting Object object.
To send back a response in the json format to your client send a ok containing a string :
/**
* Translate a json object into a json string.
*/
public static<T> String objToJson(Object obj)
{
ObjectMapper mapper = new ObjectMapper();
try{
String json = mapper.writeValueAsString(obj);
return json;
}catch(java.io.IOException e){
Logger.error(e.getMessage(), e);
}
return "";
}
public static Result actions()
{
Object objToSendBack = ...
return ok(objToJson(objToSendBack));
}
You can send back wathever you want, including html, but json is more convenient for communicating with javascript functions.
I've figure it out.
I've just changed variable response which is an object to response.responseText.
Now it works.