How to get HTML content as JSON value in spring boot - java

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>

Related

Adding additional field in Response Object

I am getting below response when I am calling an API.
Response postRequestResponse = ConnectionUtil.getwebTarget()
.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
.path("bots")
.path(ReadSkillID.readSkillId())
.path("dynamicEntities").path(dynamicEntityID)
.path("pushRequests").path(pushRequestID).path(operation)
.request()
.header("Authorization", "Bearer " + ConnectionUtil.getToken())
.get();
Below output I am getting.
{
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I have to return this output to client with an additional field in the response. How can modify the above response and make it
{
"EntityName": "NewEntity", //New field
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I am adding this additional field here
"EntityName": "NewEntity"
How can I do that. many things I tried but got exception.
get JSON from postRequestResponse (i have no idea what framework you are using, so you have to figer it out on your own, but the Response datatype will probably have a getResponseBody or similar method returing the JSON)
add EntityName
serialize it again to json.
class YourBean {
#Autowired
private ObjectMapper objectMapper;
public void yourMethod() {
// 1
final InputStream jsonFromResponse = ...
// 2
Map dataFromResponse = objectMapper.readValue(jsonFromResponse, Map.class);
dataFromResponse.put("EntityName", "NewEntity");
// 3
final String enrichedJson = objectMapper.writeValueAsString(dataFromResponse);
}
}
enrichedJson contains EntityName and whatever comes from the API.

okHTTP POST request body with many childs

I am using a charging API from a carrier, and the following JSON format has to be passed with the API call. I am using okHTTP library.
String telNum = "+941234567";
String pbody = "{\"amountTransaction\": {\"clientCorrelator\": \"7659\",\"endUserId\": \"tel:"+telNum+"\",\"paymentAmount\": {\"chargingInformation\": {\"amount\": 1,\"currency\": \"LKR\",\"description\": \"Test Charge\"},\"chargingMetaData\": {\"onBehalfOf\": \"IdeaBiz Test\",\"purchaseCategoryCode\": \"Service\",\"channel\": \"WAP\",\"taxAmount\": \"0\",\"serviceID\": \"theserviceid\"}},\"referenceCode\": \"REF-12345\",\"transactionOperationStatus\": \"Charged\"}}";```
The following is how the JSON needs to be formatted.
{
"amountTransaction": {
"clientCorrelator": "54321",
"endUserId": "tel:+94761234567",
"paymentAmount": {
"chargingInformation": {
"amount": 1,
"currency": "LKR",
"description": "Test Charge"
},
"chargingMetaData": {
"onBehalfOf": "IdeaBiz Test",
"purchaseCategoryCode": "Service",
"channel": "WAP",
"taxAmount": "0",
"serviceID": "null"
}
},
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
I get Error 400 Bad Request
Try this will format your body according to your need
try {
JSONObject jsonObject = new JSONObject(pbody);
pbody=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
OkHTTP requires RequestBody object for POST, so try this:
RequestBody body = RequestBody.create(MediaType.APPLICATION_JSON, pbody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();

Unable to parse String JSON inside post request using jersey and java

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();
}

how to retrieve a part of JSON HTTP response as POJO

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();

How do I deserialize Drupal JSON Services strings in Android?

I am using Drupal Services along with the JSON Services module as a data source.
I am using the DrupalCloud library, https://github.com/skyred/DrupalCloud/wiki, and am wondering how to best process the results that I receive from a userLogin() call.
If the call itself fails we get:
{
"#error": true,
"#message": "Some message"
}
If the call succeeds but the login credentials are wrong:
{
"#error": false,
"#data": {
"#error": true,
"#message": "Some message"
}
}
If the call success and the login credentials are correct, it returns:
{
"#error": false,
"#data": {
"sessid": "foo",
"user": {
"uid": "69",
"name": "Russell Jones",
"pass": "bar",
"mail": "russell#test.net",
"roles": {
"2": "authenticated user",
"5": "Student"
},
}
}
}
How do I go about using this data meaningfully? Or rather, how do I test to see if the call worked, and if the login was successful or not.
Have you searched older posts? Like this post, from 2 hours ago:
how to convert json object into class object
or: JSON Parsing in Android
Or just search for yourself: Search: Android+Json
Should give you a good idea..
This is one way to parse the last JSON message in your question:
public void readJsonString(String jsonString) throws JSONException
{
JSONObject jsonObject = new JSONObject(jsonString);
boolean error = jsonObject.getBoolean("#error");
if (!error)
{
JSONObject data = jsonObject.getJSONObject("#data");
String sessionId = data.getString("sessid");
JSONObject user = data.getJSONObject("user");
int uid = user.getInt("uid");
String name = user.getString("name");
// you get the pattern, same way with the other fields...
}
}

Categories

Resources