Spring won't deserialize json string (unquoted property) - java

Spring throws an error when I send json array. I am not sure what I am missing here.
RequestBody
{
"deliverySessionId":"c1fb327b-98a8-46d4-9e82-ce7507b5be93",
imageNames: ["name1", "name2"]
}
Endpoint
#RequestMapping(value = { "/examImages/" }, method = { RequestMethod.POST } )
public #ResponseBody ImageResponseCommand streamExamImages( #RequestBody ImageResponseCommand imageResponseCommand ) {
Error
The request sent by the client was syntactically incorrect.
It works fine if my request doesn't contain imageNames property.
{ "deliverySessionId":"c1fb327b-98a8-46d4-9e82-ce7507b5be93" }

Your JSON string isn't formatted properly. Object key's need to be wrapped in quotes.
{
"deliverySessionId":"c1fb327b-98a8-46d4-9e82-ce7507b5be93",
"imageNames": ["name1", "name2"]
}

Related

Parsing MultipartFile data to string in spring

I am trying to parse the MultipartFile data to string and return the string as response in java springboot. Can anyone suggest the right approach for this?
controller.java
#POST
#Path("/modelInfo")
#Produces({ "application/json" })
public Response getPretrainedModel(MultipartFile data) throws IOException {
String content = new String(data.getBytes(), StandardCharsets.UTF_8);
return Response.status(Response.Status.OK).entity(content).build();
}
file.json
{
"documents": [
{
"id": "1",
"text": "abc"
}
]
}
I am sending file.json in request body as multipart/form-data and I want to read the content of the file and store it as string.
If you are using Spring and Spring Boot, then you are not using the proper annotation. Spring does not support Jax-RS specification. Therefor, change your annotations for this one:
// #POST
// #Path("/modelInfo")
// #Produces({ "application/json" })
#PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)
Then, to return an object, you can just return the object in the method:
#PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)
public String getPretrainedModel(#RequestParam("file") MultipartFile data) throws IOException {
String content = new String(data.getBytes(), StandardCharsets.UTF_8);
return content;
}
Note:
Don't forget to add the annotation #RequestParam in your method parameter to get the uploaded file. The name file must be the name of the attribute uploaded by your POST request
By default, the HTTP Response is 200 when you don't tell Spring to send something else.
If you want to override that, annotate your method with #ResponseStatus

How to code restcontroller for google actions?

I wish to code the Rest Controller in spring-boot for my webhook. I am creating a google action, with simple actions.
This is a boilerplate: https://github.com/actions-on-google/dialogflow-webhook-boilerplate-java/blob/master/src/main/java/com/example/ActionsServlet.java.
I want to do the same, only in spring-boot. I want to manipulate JSON body as input, but not sure how to do this.
#RestController
public class indexController extends HttpServlet {
#Autowired
private App actionsApp;
//handle all incoming requests to URI "/"
// #GetMapping("/")
// public String sayHello() {
// return "Hi there, this is a Spring Boot application";}
private static final Logger LOG = LoggerFactory.getLogger(MyActionsApp.class);
//handles post requests at URI /googleservice
#PostMapping(path = "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<String> getPost(#RequestBody String payload,
#RequestHeader String header, HttpServletResponse response) throws IOException {
//Not sure what to do here.
System.out.println(jsonData);
return ResponseEntity.ok(HttpStatus.OK);
try {
//writeResponse(response, jsonResponse);
//String med request body og object that has all request header entries
String jsonResponse = actionsApp.handleRequest(body, listAllHeaders(header)).get();
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
} catch (
InterruptedException e) {
System.out.println("Something wrong happened, interupted");
} catch (
ExecutionException e) {
System.out.println("Something wrong happened, execution error");
}
}
First, there is an error in your code. There might be a wrong "return" before your function logic.
return ResponseEntity.ok(HttpStatus.OK);
Second, as you are using Spring Framework, and you use "#RequestBody String payload" in the method, the Spring Framework will take the request body and set it to payload. If you set payload as a specific type. The framework will deserialize the body to it.
Finally, you can directly use payload in your code. The value of it would be the request body.
If you want to decode the json string. You can use org.json library.
JSONObject obj = new JSONObject(payload);
String name = obj.optString("name");
The code will get the value of name in the json.

Sending raw JSON using Postman value is null

A pleasant day.
I am having trouble with simply displaying string in raw JSON format using Postman.
This is what I have in my Java code:
#RestController
public class HeroController {
#RequestMapping(method = {RequestMethod.POST}, value = "/displayHero")
#ResponseBody
public Map<String, String> displayInfo(String name){
//System.out.println(name);
Map<String, String> imap = new LinkedHashMap<String, String>();
map.put("hero", name);
return imap;
}
}
Every time I test this in Postman, I always get null (again if I am using raw format):
{
"hero": null
}
But using form-data, on the other hand, displays just what I entered.
{
"hero": "wolverine"
}
Any information, or should do in Postman to make this raw format works instead of form-data? By the way, the raw format value is JSON(application/json), and in the Header Tab, the value of Content-Type is application/json; charset=UTF-8.
Thank you and have a nice day ahead.
Try the following code for consuming the request body as JSON, in spring boot:-
#RequestMapping(value = "/displayHero", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
#ResponseBody
public String displayInfo(HttpEntity<String> httpEntity) {
String json = httpEntity.getBody();
// json contains the plain json string
// now you can process the json object information as per your need
// and return output as per requirements.
return json;
}
This code will accept json body of POST Request and then return it as response.

How to catch a JSONObject sent via POSTMAN in a Springboot application?

Following is my controller
#RestController
#RequestMapping("identity/v1/")
public class InvestigateTargetController {
#RequestMapping(method = RequestMethod.POST, value = "receive",
produces = OneplatformMediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<InvestigateOutputResource>
processRequest(#RequestBody JSONObject jsonObject) {
System.out.println(jsonObject.toString());
return new ResponseEntity<>(HttpStatus.OK);
}
}
I am trying to send a json object to this controller via POSTMAN. But when I print jsonObject.toString() the output is {} ( empty ). Following are snapshots of POSTMAN:
Where am I going wrong ?
Create a java class having properties (with getters and setters) same as json object and put it as requestbody.
Solved it. Instead of JSONObject catch it in a string type.

Could not read JSON: Unexpected end-of-input in field name

I am developing a Spring MVC web application. I am not still develop the UI. So I am testing my services using Advance Rest Client tool.
My Controller
#Controller
#RequestMapping("/testController")
public class TestController {
#Autowired
private TestService testService;
#RequestMapping(value = "/test", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public
#ResponseBody void testMethod(#RequestBody TestParam testParam) {
String tenant = testParam.getTenantCode();
String testString = tenant + " is the tenant";
}
}
TestParam.java class
public class TestParam {
private String testVar;
private String tenantCode;
public String getTenantCode() {
return tenantCode;
}
public void setTenantCode(String tenantCode) {
this.tenantCode = tenantCode;
}
public String getTestVar() {
return testVar;
}
public void setTestVar(String testVar) {
this.testVar = testVar;
}
}
I send the request using Advance Rest Client and headers and request link has set correctly.
{"testVar":"Test","tenantCode":"DEMO"}
Request link
http://localhost:8080/myApp/controller/testController/test
It works correctly when TestParam has one veriable. When it becomes two or more it gives an Error and it not hit the testMethod.
exception is com.fasterxml.jackson.core.JsonParseException: Unexpected end-of-input in field name at [Source:org.apache.catalina.connector.CoyoteInputStream#7b24d498; line: 1, column: 43]
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:181)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:173)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:135)
I went throw more articles and I still couldn't find the answer.
Increasing Content-Length: in header works
Whats your json format ? I think json format uses literal \n's as delimiters, please be sure that the JSON actions and sources are not pretty printed.
There is an issue in ARC where there is no payload and the response is of a type of json. Parser is throwing error because the string is empty and the response report is crashing.

Categories