I have the following object and its value is set via a REST call as follows.
#Getter
#Setter
public class Benefit {
#JsonProperty("text")
private String headerText; // To note, I can't modify this headerText name
}
Data set from a rest call.
ResponseEntity<Benefit> response =
template.exchange(url, HttpMethod.POST, request, Benefit.class);
Benefit benefit = response.getBody();
The return value from the rest call is in following format which is why I annotated it as text.
{
"text" : "some text"
}
After this, using this response, I am passing it down as a value to the client that called me.
But when I send the information down, I don't want to name it as text.
I want to call it as description. Thus my response will be as follows:
{
"description" : "some text"
}
Queries/ Pointers
1. Is there a way to do this without me having to manually set it?
2. This headerText is in use for different REST call. In that scenario, I need to both
receive the value as text and also return as text. (Thus that has no issues).
3. Preferably any possible solutions, should not affect above point 2.
4. But is ok if it will affect. I will go with an entirely new Benefit2 Object to resolve this if there is a solution which affects point 2.
One possible way to do this is to set the value to another variable and pass that down as follows only for the particular rest call.
But finding it very cumbersome as follows.
Add a new field called description
#Getter
#Setter
public class Benefit {
#JsonProperty("text")
private String headerText;
// add a new field
private String description;
}
After the rest call, do the following:
Benefit benefit = response.getBody();
benefit.setDescription(benefit.getHeadlineText);
benefit.setHeaderText(null);
Any better ways?
To clarify on the flow:
Client calls my service
My service calls another service and got back:
{
"text" : "some text"
}
I then return the following back to the client.
{
"description" : "some text"
}
Thoughts after discussion.
Intention to use this object in both places, when calling rest and when returning response to client.
#Getter
#Setter
public class TestBenefit extends Benefit {
#Getter(AccessLevel.NONE)
#JsonProperty("text")
private String text;
private String description;
public void setText(String text) {
this.description = text;
}
}
Over time I learned that trying to use one object for multiple purposes in these scenarios is more trouble than it is worth. You should create objects that cater to your requests and responses appropriately. Use base classes if necessary. Also, I wouldn't call it Benefit2. :o) Name your classes, to some degree, for what they are used for. You could do something like...
class BenefitForOtherPurpose extends Benefit {
#JsonProperty('description')
public String getHeaderText() {
return this.headerText;
}
}
To that end, I don't think there is a way using the Jackson API to adjust the #JsonProperty value dynamically short of some reflection kung-fu that, again, is likely more trouble than it is worth. And there's nothing I know of in the Jackson API to conditionally set that outside of this complex solution:
Conditional JsonProperty using Jackson with Spring Boot
Related
I need to ignore the field when return the response from spring boot. Pls find below info,
I have one pojo called Student as below
Student {
id,
name,
lastName
}
i am getting a body for as PostRequest as below
{
id:"1",
name:"Test",
lname:"Test"
}
i want get all the data from frontEnd (id,name,Lname) But i just want to return the same pojo class without id as below,
{
name:"Test",
lName:"Test"
}
I have tried #JsonIgnore for column id, But it makes the id column as null(id=null -it is coming like this even when i send data to id field from postman) when i get the data from frontEnd.
I would like to use only one pojo to get the data with proper data(withoud getting id as Null), and need to send back the data by ignoring the id column.
Is there any way to achieve it instead of using another pojo?
You just need to use #JsonInclude(JsonInclude.Include.NON_NULL) at class level and it will be helpful for ignore all your null fields.
For example :
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Test {
// Fields
// Constructors
// Getters - setters
}
As of now you are using only one POJO it's not good practice because it's your main entity into your project, so good practice is always make DTO for the same.
This is possible via the #JsonView annotation that is part of Jackson. Spring can leverage it to define the views used on the controller.
You'd define your DTO class like this:
class User {
User(String internalId, String externalId, String name) {
this.internalId = internalId;
this.externalId = externalId;
this.name = name;
}
#JsonView(User.Views.Internal.class)
String internalId;
#JsonView(User.Views.Public.class)
String externalId;
#JsonView(User.Views.Public.class)
String name;
static class Views {
static class Public {
}
static class Internal extends Public {
}
}
}
The Views internal class acts as a marker to jackson, in order to tell it which fields to include in which configuration. It does not need to be an inner class, but that makes for a shorter code snippet to paste here. Since Internal extends Public, all fields marked with Public are also included when the Internal view is selected.
You can then define a controller like this:
#RestController
class UserController {
#GetMapping("/user/internal")
#JsonView(User.Views.Internal.class)
User getPublicUser() {
return new User("internal", "external", "john");
}
#GetMapping("/user/public")
#JsonView(User.Views.Public.class)
User getPrivateUser() {
return new User("internal", "external", "john");
}
}
Since Spring is aware of the JsonView annotations, the JSON returned by the /public endpoint will contain only externalId and name, and the /internal endpoint will additionally include the internalId field.
Note that fields with no annotation will not be included if you enable any view. This behaviour can be controlled by MapperFeature.DEFAULT_VIEW_INCLUSION, which was false in the default Spring ObjectMapper when I used this for the last time.
You can also annotate your #RequestBody parameters to controller methods with JsonView, to allow/disallow certain parameters on input objects, and then use a different set of parameters for output objects.
Small question regarding Spring Webflux, and how to get the nested List of Pojo that is present in a http response directly.
We are consuming an API which response is something like
{
"noNeedThisField": "I do not need this",
"listOfWhatIwant": [
{
"personName": "Alice",
"personAge": "11"
},
{
"personName": "Bob",
"personAge": "22"
},
{
"personName": "Charlie",
"personAge": "33"
}
],
"uselessField": "This is useless",
"manyFieldsNoNeed": "it is one response, which contains a lot of fields that I do not need, I just need to retrieve the list DIRECTLY please",
"noNeed": true,
"anotherNotImportant": "this is not important at all"
}
Basically, it is one response, which contains a lot of fields I do not need, plus an element of type list in it, which I would like to get directly.
If I create two different classes, first one
public class PojoWithListAndOtherNoNeedFields {
private String noNeedThisField;
private List<MyNestedPojo> listOfWhatIwant;
private String uselessField;
private String manyFieldsNoNeed;
private boolean noNeed;
private String anotherNotImportant;
}
//getters setters
second one
public class MyNestedPojo {
private String personName;
private String personAge;
//getters setters
}
And invokes Webclient like this:
public Mono<PojoWithListAndOtherNoNeedFields> sendReqest() {
return webClient.mutate().baseUrl("url").build().post().uri("/route").retrieve().bodyToMono(PojoWithListAndOtherNoNeedFields.class);
}
It is working fine! I just need to carry a very large class that I do not need in my code, and retrieve the nested list of what I need with a getter each time.
However, I was wondering is it is possible to do something similar as (this is not working)
public Mono<List<MyNestedPojo>> sendReqest() {
return webClient.mutate().baseUrl("url").build().post().uri("/route").retrieve().bodyToMono(List<MyNestedPojo>.class);
}
In order to retrieve the nested element directly.
My goal is to get rid of PojoWithListAndOtherNoNeedFields entirely, and getting the List< MyNestedPojo> directly. Is it possible?
How to perform this in a proper way in Spring using the Webclient please?
Thank you
You can use the #JsonIgnoreProperties annotation to inform the ObjectMapper to ignore any fields not included in your POJO when deserialisating from json to a POJO.
#JsonIgnoreProperties(ignoreUnknown = true)
public class PojoWithListAndOtherNoNeedFields {
private List<MyNestedPojo> listOfWhatIwant;
}
public class MyNestedPojo {
private String personName;
private String personAge;
}
JavaDocs
TL;DR : Enum deserialization errors are not caught by org.springframework.validation.Errors in a Rest Controller
For reference: we didn't find a clean solution yet as we finally decided that no one should call us wit a bad enum
I have a rest controller that uses org.springframework.validation.Errors for parameter validations:
#RequestMapping(value = "/vol1/frodo")
public ResponseEntity<Object> simpleMethodUsingPost(
HttpServletRequest httpServletRequest,
#Valid #RequestBody MySimpleObject simpleObject,
Errors errors) {
/* If an error occured, I need to log the object */
if (errors.hasErrors()) {
List<FieldError> fields = errors.getFieldErrors();
doSomething(fields , simpleObject);
}
}
My class MySimpleObject looks like this:
public class MySimpleObject {
#Valid
#NotNull(message = "anObjectField is a mandatory field")
private EmbeddedObject anObjectField = null;
#Valid
#NotNull(message = "aStringField is a mandatory field")
private String aStringField = null;
#Valid
private MySimpleEnum aSimpleEnum = null;
}
And my enum class MySimpleEnum is basically a class with two values:
public enum MySimpleEnum{
ORC("ORC"),
URUK("URUK");
private String value;
MySimpleEnum(String value) {
this.value = value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}
The validation of this object (and the injection of errors in the springframework Error object) works well when it's on a String or an Object, but it will fail validation of an enum (hence an object containing a valid-annoted enum will fail too).
It fails when trying to cast the JSON String to an enum when the value is not valid:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot deserialize value of type 'lotr.middleearth.model.MySimpleEnum' from String "HOBBIT"
This deserialization error is caught if I use a ResponseEntityExceptionHandler and override handleHttpMessageNotReadable, but then I don't have access to the different other parameters and can't use them.
How can I configure either a Validator, enum or springframework Error so that this exception is caught and usable in my controller body?
I just came across the same problem but didn't like the idea of giving the user an unformatted "ugly" validation error message.
First, I made the enum property not nullable on the pojo.
#NotNull(message = "Type must be NEW_APPLICATION or RENEWAL")
private RegistrationSubmissionTypeEnum type;
Then I changed the setter to basically check the input (as a string) and see if it matches one of the enums. If not, I do nothing, the property stays null and it's reported back as one of the validation error messages (using the message text used on the #NotNull annotation).
public void setType(Object typeInput) {
for (RegistrationSubmissionTypeEnum typeEnum : RegistrationSubmissionTypeEnum.values()) {
if (typeEnum.getKey().equalsIgnoreCase(typeInput.toString())) {
this.type=RegistrationSubmissionTypeEnum.valueOf(typeInput.toString());
}
}
}
That's really the key. The normal behavior we all despise generates an ugly error message, but it also does it in a way such that this error message is displayed alone. Personally, I like to send back all errors en masse.
I'm not a fan of hardcoding the enum values on the #NotNull message, but in this particular case (small number of enum values), it's preferable to the default enum serialization error message, and the behavior of a one-off isolated error message.
I considered a custom validator, but that started to feel heavy. Maybe someone can improve on this.
The problem that is occurring is that in the enum MySimpleEnum there is no constant "HOBBIT" the possibilities are "ORC" and "URUK", in the validation question can be used simply as in the example:
#NotNull(message = "Custom message")
private MySimpleEnum aSimpleEnum
I ended up doing something like that to extract the problematic field in the request :
int start = ex.getMessage().indexOf("[\"");
int end = ex.getMessage().indexOf("\"]");
String fieldName = exception.getMessage().substring(start + 2, end)
The field happens to be at the end of the message between the brackets.
I'm not really proud of that one, it's messy, but it seems to be the only way with enums.
I guess it would be better to use strings and proper Spring validation instead, since it depends too much on the implementation and may break with future updates.
My REST service needs to return messages of format:
{
"code": 1000,
"message": "Success",
"description": null,
"data": [
{
"custId": "00000023401443",
"engName": "MISTER NORWAYTEST'S PASSPORT",
}
]
}
where the first tier of the JSON message is basically like a message header to provide technical details about message delivery while the "data" key contains the actual business information.
If I were to create a class to reflect this, I would by default come out with something that looks like this:
public class ResponseModel<T> implements Serializable{
private Integer code;
private String message;
private String description;
#JsonProperty(value = "data")
private T dataObj;
}
but doing it this way causes my controllers to all return the same object with no real business context value to the class name and reduces readability:
#GetMapping("/profile/{userId}")
public ResponseEntity<ResponseModel> getProfile(#PathVariable String userId) {
...
}
What I would like to do is to use ResponseModel as a superclass and then inherit them into subclasses with real business context names (e.g. Customer or Account). But in order to adhere to the required JSON format, I need to ensure that attributes of the subclass as wrapped into the "data" key.
Is there a way that I can do that? Using #JsonRootName would also wrap the superclass properties as well.
The problem of your the format you want is right here :
"data": *[* <---- HERE THAT BRACKET
If you want a bracket that means your data is a list so you need to fix it by making dataObj a list :
#JsonProperty(value = "data")
private List<T> dataObj;
Now i don't see the point of subclassing ResponseModel you could just do the following :
public ResponseEntity<ResponseModel> myControllerMethod(){
List<Account> list = myService.readAccounts();
return new ResponseModel<Account>(list);//default code OK,...
}
If you make your Business classes inherits ResponseModel which is only a wrapper to handle controller's result, you will be mixing your business layer with controller's specific layer which is not a good idea.
but doing it this way causes my controllers to all return the same object with no real business context value to the class name and reduces readability:
In a Java's controller, you're suppose to have very very few lines, basically, call a service, check the answer/handle exceptions, return the response. So I don't see any problem of readability because if this. If you talk about the generic returned value, just name properly your methods.
I worked out a concept to conditionally validate using JSR 303 groups. "Conditionally" means that I have some fields which are only relevant if another field has a specific value.
Example: There is an option to select whether to register as a person or as a company. When selecting company, the user has to fill a field containing the name of the company.
Now I thought I use groups for that:
class RegisterForm
{
public interface BasicCheck {}
public interface UserCheck {}
public interface CompanyCheck {}
#NotNull(groups = BasicCheck.class)
private Boolean isCompany
#NotNull(groups = UserCheck.class)
private String firstName;
#NotNull(groups = UserCheck.class)
private String lastName;
#NotNull(groups = CompanyCheck.class)
private String companyName;
// getters / setters ...
}
In my controller, I validate step by step depending on the respective selection:
#Autowired
SmartValidator validator;
public void onRequest(#ModelAttribute("registerForm") RegisterForm registerForm, BindingResult result)
{
validator.validate(registerForm, result, RegisterForm.BasicCheck.class);
if (result.hasErrors()
return;
// basic check successful => we can process fields which are covered by this check
if (registerForm.getIsCompany())
{
validator.validate(registerForm, result, RegisterForm.CompanyCheck.class)
}
else
{
validator.validate(registerForm, result, RegisterForm.UserCheck.class);
}
if (!result.hasErrors())
{
// process registration
}
}
I only want to validate what must be validated. If the user selects "company" fills a field with invalid content and then switches back to "user", the invalid company related content must be ignored by the validator. A solution would be to clear those fields using Javascript, but I also want my forms to work with javascript disabled. This is why I totally like the approach shown above.
But Spring breaks this idea due to data binding. Before validation starts, Spring binds the data to registerForm. It adds error to result if, for instance, types are incompatible (expected int-value, but user filled the form with letters). This is a problem as these errors are shown in the JSP-view by <form:errors /> tags
Now I found a way to prevent Spring from adding those errors to the binding result by implementing a custom BindingErrorProcessor. If a field contains null I know that there was a validation error. In my concept null is not allowed - every field gets annotated with #NotNull plus the respective validation group.
As I am new to Spring and JSR-303 I wonder, whether I am totally on the wrong path. The fact that I have to implement a couple of things on my own makes me uncertain. Is this a clean solution? Is there a better solution for the same problem, as I think this is a common problem?
EDIT
Please see my answer here if you are interested in my solution in detail: https://stackoverflow.com/a/30500985/395879
You are correct that Spring MVC is a bit picky in this regard,and it is a common problem. But there are work-arounds:
Make all your backing fields strings, and do number/date etc conversions and null checks manually.
Use JavaScript to set fields to null when they become irrelevant.
Use JavaScript to validate fields when they are entered. This will fix almost all of your problems.
Good luck!
I know this question is old, but I came upon it looking for an answer for a different situation.
I think for your situation you could use inheritance for the forms and then use two controller methods:
The forms would look like this:
public class RegistrationForm
{
// Common fields go here.
}
public class UserRegistrationForm
extends RegistrationForm
{
#NotNull
private String firstName;
#NotNull
private String lastName;
// getters / setters ...
}
public class CompanyRegistrationForm
extends RegistrationForm
{
#NotNull
private String companyName;
// getters / setters ...
}
The controller methods would look like this:
#RequestMapping(method = RequestMethod.POST, params = "isCompany=false")
public void onRequest(
#ModelAttribute("registerForm") #Valid UserRegistrationForm form,
BindingResult result)
{
if (!result.hasErrors())
{
// process registration
}
}
#RequestMapping(method = RequestMethod.POST, params = "isCompany=true")
public void onRequest(
#ModelAttribute("registerForm") #Valid CompanyRegistrationForm form,
BindingResult result)
{
if (!result.hasErrors())
{
// process registration
}
}
Notice that the #RequestMapping annotations include a params attribute so the value of the isCompany parameter determines which method is called.
Also notice that the #Valid annotation is place on the form parameter.
Finally, no groups are needed in this case.