Custom json with Swagger - json

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.

Related

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

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

Multiple custom serializers for same entity in Spring Boot

I'm working on a Spring Boot application. I've created a custom serializer for one entity A and registered it using #JsonSerialize(using = CustomSerializer.class) annotation. Whenever i send A in ResponseEntity<> the custom serializer is called and everything is working fine till this point.
Now there is another API in which i need to send a Collection of A in response. But i cant use same serializer to construct the list of A's as response parameters are totally different. I need to write one more serializer for same entity .
How can i configure 2 serializers for same entity? They should be called based on the object type sent in response i.e. When i'm sending A, then serializer1 should be called and when i'm sending Collection, the serializer2 should be called.
Please help!
A simple workaround would be to annotate the collection to use a specific serializer for content. E.g.
#JsonSerialize(using = CustomSerializer.class)
class A {
}
class AList {
#JsonSerialize(contentUsing = AnotherCustomSerializer.class)
private final List<A> list;
}

Spring MVC #RequestBody and partial object/json binding

I have a large object which can be updated in a few steps. I'am facing a partial binding problem. My service consumes json and I can not use #InitBinder along with #RequestBody. Cutting this object to a few small ones is not good a solution, because there is a lot of cross-field validations between steps.
Do you have any ideas how to solve this? I'am looking for a clean solution like: registering a specific object mapper for given #RequestMapping or something like that. Thanks for help.
You should be able to use a PATCH HTTP method
Its the preferred method that you would use when you need partial updates, like in your case when you want to update just a few fields of a resource
Spring MVC added a support for it in the version 3.2, so you can do something like
#RequestMapping(value="/patch", method=RequestMethod.PATCH, consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String patch(#RequestBody Foo foo) {
return foo.toString();
}
and when sending the request, add only the properties you want to update to your PATCH request, the properties that are null or omited won't be updated
In the lack of better Spring MVC PATCH reference, I'm linking this SO thread as an interesting read Spring MVC PATCH method: partial updates

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() {
...
}

List<Object> to JSON using annotations

OK, here goes, hopefully this makes sense! I have a small project based off of the appfuse web service only archetype. I have a business facade which has a DAO injected, through this DAO I request some data, simple example:
PersonManager.java
#GET
#Path("{people}")
List<Person> getPeople(#QueryParam("surname") String surname);
PersonManagerImpl.java (implements PersonManager)
public List<Person> getPeople(String surname) {
return personDao.getPeople(String surname);
}
I can make a request to invoke this method through a URL configured to point to "getPeople", however, as the DAO returns the list of people as an array list, I get the following error
Error serializing the response, please check the server logs, response class : ArrayList.
I know I can wrap this method and use Jackson Object Mapper to change the list to a string, but I didn't want another layer in my code, just to marshal JSON requests/responses.
I also don't want to change the interface to return a string, because the interface may be used later to return other data types, thus, I don't want to lock it in to only returning a string representing JSON.
My dilemma is that, I don't quite get how keeping the above interface and implementation, I can have Jackson convert the list of people to a json list of people, with annotations only!
Any help is greatly appreciated.
Please help!
Upgrading Jackson from 1.7.1 to 1.9.5 resolved this issue.