The following will include only fields that have the JsonView(View.MyView.class) annotation:
#JsonView(View.MyView.class)
#RequestMapping(value = "offer", method=RequestMethod.POST)
public ResponseEntity<MyResponse> offer(...) {}
Question: how can I negate it? Means: include any field except the ones having JsonView(View.MyView.class)? Especially without having to add another annotation on any of the remaining fields?
It's not possible. But by adding the following property, any fields not having a #JsonVniew annotation will be serialized:
spring.jackson.mapper.default-view-inclusion=true
As a result, only a #RequestMapping #JsonView will output only non-annotated fields plus the ones matching the view.
So if I want to exclude only some fields inside a specific view, I just have to give the to be excluded fields a different view that is not used in the #RequestMapping. Then they are ignored automatically.
Related
I need to add #Json non-null in call level but I am not able to do it from swagger code gen.
Hence, could you please help me with this issue?
you can use the #io.swagger.v3.oas.annotations.media.Schema annotation on your method parameters. This annotation allows you to specify the data type, format, and other properties of the parameter, and you can use it to specify that the parameter is required (non-null) using the required property.
Here is how you might use the #Schema annotation to specify that a method parameter is required:
#GET
#Path("/users/{id}")
public User getUser(
#PathParam("id") #Schema(required = true) String userId
) {
...
}
In this example, the #Schema annotation is used on the userId parameter to specify that it is required. This will ensure that the generated code includes the #Json non-null annotation on the parameter, which will enforce the requirement at runtime.
You can also use the #Schema annotation to specify other properties of the parameter, such as its data type, format, and description. For more information, you can refer to the Swagger Code Gen documentation.
I am using Immutables-value for defining my POJO. And when it generates the Immutable* class, it has the #Generated annotation at the top. Is there any way I could disable it?
I checked in their codebase:
https://github.com/immutables/immutables/blob/master/value-annotations/src/org/immutables/value/Generated.java#L22-L27
It is mentioned here that it can be disabled by :
Style#allowedClasspathAnnotations()
I used it on top of POJO interface like this:
#Value.Style(allowedClasspathAnnotations = {org.immutables.value.Generated.class})
But still I am getting the #Generated annotation on top of my generated class. Any idea how can I do this?
#Style's allowedClasspathAnnotations attribute whitelists the annotations you included there (Rather than blacklisting them). See here.
So if you want to only disable org.immutables.value.Generated you should instead do something like:
#Value.Style(allowedClasspathAnnotations = {
javax.annotation.concurrent.Immutable,
javax.annotation.ParametersAreNonnullByDefault,
javax.annotation.CheckReturnValue,
edu.umd.cs.findbugs.annotations.SuppressFBWarnings,
com.google.errorprone.annotations.Var,
com.google.errorprone.annotations.Immutable
})
To whitelist the annotations you want to keep.
I'm implementing an in-memory API gateway to a SOAP service utilizing JAXB. One of the schema elements is a "choice", and there are several elements in the choice block.
I'm attempting to mirror the generated JAXB classes in the client namespace, so for this "choice" scenario I have a bean class with several properties, only one of which will be non-null.
I'm attempting to use the #NotNull annotation from javax.validation, along with the ValidatorFactory and Validator. However, a "choice" scenario makes this a little more complicated. I'm guessing this would call for a custom ConstraintValidator, along with a custom annotation to refer to the custom ConstraintValidator.
For instance, here's some fake code that resembles a part of my structure:
public class InquireRandomInformationRequest {
#NotNull(message ="subscriberSelector cannot be null")
#Valid
private SubscriberSelector subscriberSelector; // required
private SelectorMode mode; // optional
...
}
public class SubscriberSelector {
// Choice 1
private String billingAccountNumber; // \d{8,9,12,13}; required
private MarketInfo billingMarket; // optional
// Choice 2
private String subscriberNumber; // \d{10}; required
private ValidationCriteria validationCriteria; // optional
private BillingAccountInformation billingAccountInformation; // optional
private MemoProductType memoProductType; // optional
// Choice 3
private String unifiedBillingAccountNumber; // [0-9A-Za-z]{13}; required
...
}
I understand that I need the #Valid annotation on the "subscriberSelector" property for the validator to validate the sub-object. Past that, I'm not quite sure what I need to do to handle the choices problem.
To fit my example, I will need exactly one of "billingAccountNumber", "subscriberNumber", or "unifiedBillingAccountNumber" to be non-null (although I could compromise on simply taking the first non-null one in a particular sequence). In each "choice group", the other properties are optional, but it's possible that another property could be "required" if that particular choice group is selected (the selector property is non-null, in other words).
I've looked through the Hibernate Validator documentation, but I'm not sure exactly how to apply that for this situation.
If I define a custom annotation and a custom ConstraintValidator, where is the annotation referenced? On the class (like "SubscriberSelector") or on the "subscriberSelector" property (the former seems more logical to me).
You can define constraints on the class or on the property depending on your requirements.
Usually, the constraints are placed on the property but, in the case you mention, as multiple properties are concerned and interdependent, you should place the constraint at the class level.
See https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-declaring-bean-constraints in our documentation.
I got a list that return from below db call.
List<employee> list = empolyeeRepository.findByEmployeeId(id);
List contains employee pojo class object. I want to remove one attribute let's say "employee bank account no" when returning from rest call.
#RequestMapping(value = "/employeeInformation/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public List<Employee> getEmployeeInformation(#PathVariable("id") String id) throws Exception {
return empolyeeRepository.findByEmployeeId(id);
}
Is there any annotation or good practice to do that?
As it mentioned in comments above, you cant remove fields of compiled class at runtime. Assuming you have to exclude some field from generated json, there I see two options:
Create a class with fields you want to be present in resulting json, copy required values from original object to a new created. This approach is called view model and allows you to decorate some object's data, hiding sensitive data from being exposed.
Depending on implementation of your serializer there may be annotations to exclude fields. #JsonIgnore may be placed on getter method, if you are using Jackson (default in spring boot). Second aproach requires significant less code, but the first one is more flexible.
Try #JsonIgnore to ignore properties from serialization and de-serialization.
Here is the link to the docs
In java tutorials - Annotations part, question 3 (https://docs.oracle.com/javase/tutorial/java/annotations/QandE/questions.html), an annotation are expected to be used as below:
#Meal("breakfast", mainDish="cereal")
I tried to define the annotation as below but it does not allow the above usage.
public #interface Meal {
String value();
String mainDish();
}
Is it possible to omit the first attribute name as the question suggested?
No, the shortcut only works if you specify the value attribute and nothing else.
Otherwise you must explicitly write value=, that is the correct version would be #Meal(value = "breakfast", mainDish = "cereal")