Expose a Springboot rest endpoint to read json object - json

I am new to Springboot and Webservices.Using springboot i need to expose a rest endpoint. Some data provider will call the rest endpoint to post the data. Then i need to start processing the posted json and convert it into a java object. So using spring boot I need to expose a rest webservice to accept and process the json posted to the webservice created. How should I do it. Any example would help

Its so simple.
We need to have a Springboot restcontroller to expose rest endpoint. And then using #Requestbody we need to get the Objects directly from the json message passed .
#RestController
public class JsonObjectRestController {
#RequestMapping(value="/rest/pushjson",method = RequestMethod.POST)
public ResponseEntity<PushedJsonObject> getJsonObject(#RequestBody PushedJsonObject jsonObject)
{
if(jsonObject != null)
{
//process the json object
}
return new ResponseEntity<PushedJsonObject >(jsonObject, HttpStatus.OK);
}
}
Explanation:
We need to have a model class representing the json sent(Here its PushedJsonObject). Have your controller annotated with the new Spring4 #RestController.
The #RequestBody method parameter annotation should bind the json value in the HTTP request body to the java object by using a HttpMessageConverter. Make sure Jackson is in the classpath so that spring boot configures it automatically to use the MappingJackson2MessageConverter.

Related

How to accept json data though post in spring boot rest

PostMapping method
#RestController
#RequestMapping("/validate")
public class Validatesimapi {
#PostMapping
public Simoffers validateSim(#RequestBody ???)
}
I want to pass following json object through post request and accept it in validateSim. What should I write at ???.
{
"id": "1234",
"num":"2343335"
}
both the datatypes of id and num is String.
enter code here
It’s as simple as adding a DTO with the fields that you want. The Jackson mapper will map the json to that object.

How to configure spring boot for using klaxon library

There is a klaxon library - JSON parser for kotlin
How to configure Spring Boot for using it to make a REST API in this way:
#RestController
class SampleController {
#RequestMapping("/test", method = [RequestMethod.POST])
fun test(#RequestBody body:JsonObject): JsonObject {
//work with body val (KLAXON object)
//return KLAXON object
}
}
#RequestBody body:JsonObject - is a Klaxon object, so we do not want to use standard Jackson2ObjectMapperBuilder for RequestBody. For simplicity we do not want to use it for Response body too.
Post body is some kind of dynamic data, so I want to use a Low level API in lib, not a Object binding API.
No, at the moment it's not possible.
Reference

Spring MVC : post request and json object with array : bad request

I'm trying to retrieve parameters from a http POST request with Spring MVC.
The request contains the following json object (content-type : application/json), which itself contains an array of customObjects :
{
"globalId":"338",
"lines":[
{
"id": "someId",
"lib":"blabla",
...
}
]
}
Here's the code I'm trying to use :
#RequestMapping(method = RequestMethod.POST, value = "/valider")
#ResponseBody
public void valider(final HttpServletRequest request, #RequestParam("globalId") final String globalId, #RequestParam("lines") final MyCustomObject[] lines) {
All I'm getting is a "bad request" error (http 400).
Is it possible to separately retrieve the two parameters "globalId" and "lines" ? Or since they are in the same json object, it has to be treated has a single parameter ? How do you proceed when you have more than one parameter in a Post request ?
I think you're looking for something like `#RequestBody. Create a class to represent your JSON data. In your case, this class will contain two member variables - globalId as a string and lines as an array of the object it represents. Then in your controller method, you will use the #RequestBody annotation on this class type so that Spring will be able to convert the JSON into object. Check the examples below.
http://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/
JQuery, Spring MVC #RequestBody and JSON - making it work together
http://www.techzoo.org/spring-framework/spring-mvc-requestbody-json-example.html
create model object to map your Json data
class DLibrary{
int id;
String lib;
//getters/setters
}
class GLibrary{
int globalId;
List<DLibrary> lines;
//getters/setters
}
Replace your controller code with below
#RequestMapping(method = RequestMethod.POST, value = "/valider")
#ResponseBody
public void valider(#RequestBody GLibrary gLibrary) {
#RequestBody annotation will map Json to Java Object implicitly.
To achieve this spring must require jackson-core and jackson-mapper library included in your application and your Java class should have getter and setters i.e it must follow bean standards.
Indeed, I have to use #RequestBody to get the JSON object.
Quick summary, depending on how the parameters are passed in the http POST body request :
one JSON object (Content-Type: application/json), use #RequestBody to map the json object to a java object
multiple parameters (Content-Type: application/x-www-form-urlencoded), use #RequestParam for each parameter

JSON respones from Jersey 1.x (1.17) with JAXB cannot be deserialized by Jackson

I have a jersey webservice running 1.17 and supports returning responses via both XML and JSON via the #Produces annotation. I am assuming it uses JAXB by default when returning JSON responses but I have no way to confirm it. As of now, my existing clients also use the same JAXB serializer/deserializer. I want to create a new client that uses Jackson without impacting the existing clients.
The JAXB JSON response is incompatible for Jackson for Maps. the JSON for a map using JAXB is of the form
"mapName":{"entry":[{"key":"key1","value":"value1"},{"key":"key2","value":"value2"}]}
and Jackson fails to parse this. Is there any way to make jackson parse this JSON?
Another Attempt: Switching Jersey to use Jackson
This isn't the preferred option but I tried setting "com.sun.jersey.api.json.POJOMappingFeature" to true to allow it to use Jackson for JSON Serialization/Deserialization however the service ends up returning 500s on response without logging any exceptions. the log4j logger level is set to TRACE. I enabled the ContainerRepsonseFilter to confirm 500s in the response and to my surprise, it logs the successful 2xx response. My guess is the problem occurs somewhere further down the stack but I don't know where.
I ended up with using MOXy which is able to parse the above json format.
#Provider
public class JsonMoxyConfigurationContextResolver implements ContextResolver {
private final MoxyJsonConfig config;
public JsonMoxyConfigurationContextResolver() {
final Map<String, String> namespacePrefixMapper = new HashMap<String, String>();
namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
config = new MoxyJsonConfig()
.setNamespacePrefixMapper(namespacePrefixMapper)
.setNamespaceSeparator(':');
}
#Override
public MoxyJsonConfig getContext(Class<?> objectType) {
return config;
}
}
and enabled it Jersey 2.x client using
cc.register(JsonMoxyConfigurationContextResolver.class);

How to get a JSON object and map it into object in spring 3.0 controller using POST method?

I want to add request mapping my controller which gets a Json of Array of an object.
The JSON will be sent from javascript using post.
Thanks,
Kfir
You can do this using Spring's #RequestBody annotation, e.g.
#ResponseBody
public Map<String, Object> handleJsonPost(#RequestBody Map<String, Object> requestJson) {
...
return responseJson;
}
This will also send the return value back as JSON.
You'll also need to include the Jackson library in your application's classpath, and add
<mvc:annotation-driven/>
to your context (see docs)