JSON encoding using produces={"application/json; charset=UTF-8"} and ObjectMapper - json

I am trying to develop a microservice using Spring MVC and Spring Boot. In my service I am giving result back as JSON encoded format. Currently I added action like:
#RequestMapping("/checkUsers")
public String checkLogin() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
List<Users> useObj = (List<Users>) userRepo.findAll();
return(mapper.writeValueAsString(useObj));
}
And now I found the other options through the following method
produces={"application/json; charset=UTF-8"}
Here I am not sure which method is properly using for encoding the data into JSON format in Spring. How can I proceed?

Why don’t you just use
ResponseEntity
And return
new ResponseEntity<String>(“your message”, HttpStatus.OK);

#RequestMapping(method = GET, value = "my/random/uri", produces = "application/json;charset=UTF-8")
Here produces attribute inside my #RequestMapping annotation is the producible media types of the mapped request. The format is a single media type or a sequence of media types, with a request only mapped if mentioned one matches one of these media types. and here, my #RequestMapping annotation is already serving my purpose of encoding.
Now somewhere from Spring Boot documentation:
Spring Boot is a brand new framework designed to simplify the bootstrapping and development of a new Spring
application. The framework takes an opinionated approach to
configuration, freeing developers from the need to define boilerplate
configuration.
Please don't kill the purpose of Spring Boot. :)
Additionally, I would suggest you use org.springframework.http.MediaType class. It has got all encoding types you'll ever require. Happy coding.
Please let me know if you face any difficulty while going with suggested approach.

If you use #RestController on your controller, all request mappings will produce application/json by default.
Also, there is no need to to the object mapping yourself, just return the object without mapping and let Spring/Jackson do its thing.
#RestController
public class UsersController {
// #RequestMapping("/checkUsers")
// There is an even simpler and more concise
#GetMapping("/checkUsers")
public List<User> checkLogin() throws JsonProcessingException {
return userRepo.findAll();
}
}

Related

When is manual mapping using Jackson's ObjectMapper needed for converting pojo to json in Spring Rest's #ResponseBody annotated controller method?

I want to know what is the rule followed by MappingJackson2HttpMessageConverter to convert the object (returned from controller method annotated by #ResponseBody) to a json? In some situations I see that just having Jackson2 on classpath (pom.xml) is enough and the controller simply returns back its object e.g. String or a collection e.g. List<Employee> successfully to browser in json format. But, in other cases I have seen that the solution asks me to use an ObjectMapper and use method writeValueAsString to get a string and return that as a response, example HashMaps! Are there some implicit rules which MappingJackson2HttpMessageConverter uses to decide if it is able to do the conversion on its own or I need to manually do it using Objectmapper ? If I have a pojo object, which internally has few String fields, would I still need to use ObjectMapper etc? If not then would I need it if my pojo class has fields like , some List<CustomObject> and some HashMaps?
For example : example 1 does not use any ObjectMapper to convert List<Company> to json in controller method. But, example 2 needs an ObjectMapper and writeValueAsString ? plus, it's return type now is String instead of a HashMap!
If you use #RestController and you have jackson in the class path everything will be handled OK. see https://spring.io/guides/gs/rest-service/ and https://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/

Custom json with Swagger

I'm using Spring boot with Swagger 2(using springfox to wrapper).
I have a big entity that a lot of fields is filled automatic at server side and I have a service to store them. Instead of swagger show all the attributes of this entity like this
I want to show a custom json to store this entity, if possible I would like to show the attributes to send like this
My controller:
#RequestMapping(value = "/cadastrar", method = RequestMethod.POST, produces= "Application/JSON")
public ResponseEntity<?> cadastrarUsuario(#RequestBody #Valid AcessoUsuario usuario, BindingResult result) {
..
}
Please someone could help me? I'm a little lost how to do this with Swagger.
If you don't like all the auto-detected, public fields in your model, you have two choices.
Define an interface that shows what you are interested in, and map that to the operation that is either consuming or producing that entity.
Create a custom model processor which handles types as you like.

Dropwizard good practices

I have seen in a lot of places that a resource class in a dropwizard project has methods for GET and POST. These methods then access data from the database using the DAO and return back a json
public class DropwizardResource {
private DropwizardDAO ddao;
public DropwizardResource (DropwizardDAO ddao) {
this.ddao = ddao;
}
#GET
#Timed
#UnitOfWork
public List<String> getAllResources() {
return ddao.findAll();
}
}
Is it advisable to have a resource initialized with other clients for some other service and then have the json returned by manual conversion?
public class DropwizardResource {
private NonDbClient client;
public DropwizardResource (NonDbClient client) {
this.client = client;
}
#GET
#Timed
#UnitOfWork
public List<String> getAllResources() {
return toJson(client.findAll());
}
}
First off, let's be clear: you can do whatever you like in a Dropwizard resource - there's nothing inherently special about them.
On your specific question on whether you can use "[a client] for some other service" (e.g. another Dropwizard service, or something completely separate), the answer is yes, that's perfectly fine. Note, however, if you're not using Hibernate to access a database within your resource method, you don't need the #UnitOfWork annotation (which is for declaring that a session & transaction should be managed for you when that method is called).
Finally, you ask whether it's okay to "then have the json returned by manual conversion". It's a little hard to answer that question without knowing what client you're thinking of using, and what it returns when you call its findAll method. I can think of a couple of possible scenarios:
You get deserialised plain old Java objects back from your client (regardless of how they were serialised in transit - JSON, XML, crazy proprietary binary protocol, whatever). In this case, you just need to transform these into whatever object you want to return from your Dropwizard resource method (a List<String> in the case of your example). From there, Jersey and Jackson will deal with serialising this to JSON for you and putting that in the response from your resource.
You get a string containing JSON back from your client. In this case, you'll need to manually deserialise the JSON to Java objects (using a Jackson ObjectMapper - you can grab one from the Dropwizard Environment in your application's run method). At that point you can transform then and return them as in the above case.
In either case, I can't think why you'd want to be serialising to JSON (as in your example). That'd give you a String (not a List<String>). Unless you're doing something pretty quirky, you probably don't want to be returning a JSON string from your Dropwizard resource - that will then serialise it as JSON again, and will then result in a string full of JSON being deserialised again at the other end!

Mobile application + Spring MVC - JSP?

I've got a web application built over Spring MVC, already working. I'm planning to give mobile users an app for communicating with the server, so they will find easier to interact with it. I've got the Model, the Views and the Controllers working fine, but everything was designed from the web's perspective.
So, I'm building up a few new Controllers for the mobile app, and here comes the question: since the ultimate rresponsible of the View is going to be the mobile app in question, where should I delegate everything to the app, in the Controller (preparing there a JSON for each response)? Or should I have a JSP with some JSON taglib enabled, so that the Controller gives the pieces to the JSP, and then I build the JSON response in the JSP?
I'm not clear about the MVC architecture on this scenario.
Thanks in advance.
When all you are doing is creating a REST API which mobile (or other clients) are going to use, Views do not come into play. It's the responsibility of the Controller to prepare the appropriate response for the client.
Luckily since returning JSON is such a common scenario, Spring MVC transparantly handles the serialization into JSON (using the Jackson library) so you don't have to.
As JB Nizet showed, you can use the #ResponseBody annotation to tell Spring MVC that the response should be returned as is (serialized to JSON because of the produces = MediaType.APPLICATION_JSON_VALUE) or if you are using Spring 4, you can completely ditch the #ResponseBody annotation and annotate your Controller with #RestController (which makes Spring behave as if #ResponeBody was added to every method mapping) instead of #Controller.
The controller methods should simply return obejcts (or collections of objects), that will be serialized to JSON automatically thanks to the #ResponseBody annotation:
#RequestMapping(value = "/api/users",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> listUsers() {
...
}

Way to Consume Json request as Json object in Jersey Rest Service

Hi I tried googling around but cannot find solution that I want to achieve.
Example to map json to java object we do
#POST
#Consumes(application/json)
#Produces(application/json)
public Response createUpdateDeleteManualClinicalData(MyJavaPojo definedPojo) {
// this maps any json to a java object, but in my case I am dealing with generic json structure
}
What I want to achieve is Keep it as json object itself
public Response createUpdateDeleteManualClinicalData(JSONObject json)
Work around: I can get data as plain text and convert that to json. But its an overhead from my side which I want to avoid.
Edit: I am open to using any Json library like JsonNode etc... as far as I get Json object Structure directly without the overhead of String to Json from my side. This should be common usage or am I missing some core concept here.
It was a straight solution that I happened to overlooked... my bad.
Jersey is way smarter than I thought... curious to know what magic happens under the layers
#POST
#Consumes(application/json)
#Produces(application/json)
public Response createUpdateDeleteManualClinicalData(JsonNode jsonNode) {
//jsoNode body casted automatically into JsonNode
}
What is the web.xml configuration you are using? Is it something similar to here web.xml setup gists for Jersey1 and Jackson2?
If you are using the same configuration as web.xml setup gists for Jersey1 and Jackson2, then you may do as below. This is a possible alternative than using JSONObject
#POST
#Path("/sub_path2")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Map<String,Object> saveMethod( Map<String,Object> params ) throws IOException {
// Processing steps
return params;
}