How to send json Object in http post request in Java - java

I am trying to send below code as Json array in post request , Here is my Json:
*{
"date": "2019-01-01",
"source": {
"type": "calendar"
},
"device": {
"type": "mobile"
}
}*
Here is my code
**JSONArray array1 = new JSONArray();
JSONArray array2 = new JSONArray();
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject obj3 = new JSONObject();
obj.put("date","2019-01-01");
obj2.put("type","calendar");
obj3.put("type","mobile");
array1.put(obj2.toString());
obj.put("source",array1.toString());
obj.put("device",array2.toString());**
Now i want to send this object in post request. How do i do that?
HttpRequest request = HttpRequest.newBuilder().POST(obj)
here how can i send the "obj" in post request

Using MockMvc, as an example, will be like this:
[...]
ObjectMapper objectMapper;
MvcResult result =
mockMvc
.perform(post(URL)
.headers(headers)
.content(objectMapper.writeValueAsString(MY OBJECT)))
.andDo(print())
.andExpect(status().isCreated())
.andReturn();
I've used this example code in my tests project. I guess ObjectMapper will help you! :)

Related

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

How to get HTML content as JSON value in spring boot

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>

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

Mapping a trimmed response using ObjectMapper Or wrapping the response obtained

Details ---
One of my POJO SomeResponseObject for an api response has attribute
#JsonProperty("s_summary")
private Map<String, SummaryObject> summary
which further has few more attributes. These are summed in json as follows :
{
"s_summary": {
"rewardSubscription": {
"accountId": "XYZ",
"startDate": "2015-12-29T19:00:00+05:30",
"endDate": "2017-06-21T00:00:00+05:30",
"isActive": true,
"entityId": "ID123",
"status": "ACTIVE"
}
}
}
This POJO(json) is further modified by our service to return a RESPONSE as :
{
"rewardSubscription": {
"accountId": "XYZ",
"startDate": "2015-12-29T19:00:00+05:30",
"endDate": "2017-06-21T00:00:00+05:30",
"isActive": true,
"entityId": "ID123",
"status": "ACTIVE"
}
}
Narrowing Down ---
Now when we are writing tests against this API call. We end up being unable to map the response to any specific POJOs(java response class). Test code -
JSONObject responseObject = new JSONObject(responseFromService.getResponseBody())
.getJSONObject("RESPONSE");
ObjectMapper objectMapper = new ObjectMapper();
SomeResponseObject summaryResponse = objectMapper.getObjectMapper()
.readValue(responseObject.toString(), SomeResponseObject.class); // And this wouldn't work.
Question --
Is there any way we can cast the current API response or wrap it somehow to be mapped to the actual POJO(SomeResponseObject.class)?
Thanks in advance.
Problem
You receive an object with a rewardSubscription field, or, in your case, a map, with a rewardSubscription key. You can't convert a map to an object of SomeResponseObject type directly.
Solution
Option 1
Convert json to a map manually and set it to the SomeResponseObject instance:
JSONObject responseObject = new JSONObject(responseFromService.getResponseBody())
.getJSONObject("RESPONSE");
ObjectMapper objectMapper = new ObjectMapper();
Map<String, SummaryObject> summaryMap = objectMapper.readValue(responseObject.toString(), new TypeReference<Map<String, SummaryObject>>() {});
SomeResponseObject response = new SomeResponseObject();
response.setSummaryMap(summaryMap);
Option 2
So as not to manually convert map each time, write a custom deserializer that will handle both cases. The deserialize method should be similar to this:
#Override
public SomeResponseObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = jp.readValueAsTree();
JsonNode sSummaryNode = rootNode.get("s_summary");
if (sSummaryNode != null) {
// Usual case.
return objectMapper.treeToValue(sSummaryNode, SomeResponseObject.class);
} else {
// Special case - when received a map.
Map<String, SummaryObject> summaryMap = objectMapper.readValue(rootNode.toString(), new TypeReference<Map<String, SummaryObject>>() {});
SomeResponseObject response = new SomeResponseObject();
response.setSummaryMap(summaryMap);
return response;
}
}
And then in the code you don't care:
ObjectMapper objectMapper = new ObjectMapper();
SomeResponseObject response = objectMapper.readValue(json, SomeResponseObject.class);

How to update a playlist using SoundCloud api wrapper for java

The soundcloud documentation has no sample for updating a playlist using java wrapper. I tried something like this but it didn't update the tracks. And no error messages returned.
HttpResponse resp = wrapper
.put(Request.to("/me/playlists/123")
.with("playlist[title]", "updated title", "playlist[tracks]", "[
{id: 10001},
{id: 10002}
]"));
Any ideas?
The problem is that you're using a mix of Rails style form parameters and JSON.
There are two options:
1) Only use form parameters:
HttpResponse resp = api.put(Request.to("/playlists/123")
.with("playlist[title]", "updated title")
.with("playlist[tracks][][id]", 10001)
.with("playlist[tracks][][id]", 10002));
2) Submit playlist data as JSON:
private void updatePlaylist() {
JSONObject json = createJSONPlaylist("updated title", 10001, 10002);
HttpResponse resp = api.put(Request.to("/playlists/123")
.withContent(json.toString(), "application/json"));
}
private JSONObject createJSONPlaylist(String title, long... trackIds) throws JSONException {
JSONObject playlist = new JSONObject();
playlist.put("title", title);
JSONObject json = new JSONObject();
json.put("playlist", playlist);
JSONArray tracks = new JSONArray();
playlist.put("tracks", tracks);
for (long id : trackIds) {
JSONObject track = new JSONObject();
track.put("id", id);
tracks.put(track);
}
return json;
}
Check out the tests in the wrapper to see them in action:
without JSON
with JSON

Categories

Resources