Handle Json non existent keys spring boot - java

I am creating a requestModel and let say a person doesn't send me some keys.
If that key is not present I want to put null if i get the value of the key.
I don't want to investigate if a key is present or not .
public class CustomerModel {
private Optional<String> s3Bucket;
private Optional<String> docType;
public String getS3Bucket() {
if(s3Bucket.isPresent()) {
return s3Bucket.get();
} else {
return null;
}
}
public void setS3Bucket(Optional<String> s3Bucket) {
this.s3Bucket = s3Bucket;
}
public Optional<String> getDocType() {
return docType;
}
public void setDocType(Optional<String> docType) {
this.docType = docType;
}
}
Do we have any library or something where.
1. If i get the key and it is not present in the coming request json, i will get the null out of it and if the key is present and has value . It will be stored as value.
2. When writing the getter for s3bucket (getS3Bucket), i dont want to write it for everykey value. Is there a automatic way to do this.
I looked at lot of posts but the scenario is not there.
P.S - I am new to java

I believe Jackson is exactly what you need. And if you are using Spring - it already uses Jackson under the hood I guess.
Here you can find some examples and documentation of how JSON mapping on to model class is done.
If you need to customize some behavior, you can use annotations like #JsonProperty (there are many).
If properties in your model class have the same names as properties in JSON, most probably you won't need to provide any further configs.
Here is a simple example:
public class User {
#JsonProperty("userName")
private String name;
private int age;
// getters and setters
}
And if you have JSON like this:
{
"userName" : "Foo Bar",
"age" : 18
}
Jackson will do all the magic for you unless you need something very specific.
If something is not in JSON you get (let's say you received JSON without age) - corresponding property in model class will be null if it is object type and default value (0, false, etc.) for primitives (in our case age would be 0).

Related

How to perform Data Type validations for each individual fields of a POJO in Java?

I have a Request POJO class which comes with all String data type fields. When I have to store them to DB, the data types must be accurate. Considering that I need to validate and convert my each individual POJO fields to the respective data types. Also, Request POJO might consists of more than 200 fields. How can I validate and convert each of my field?
This is what my Request POJO Looks like ->
#Data
public class ProductRequest {
private String goodScore;
private String invalidScore;
private String income;
private String salary;
private String updatedOn;
}
This is my Response POJO should look like, these are the types I actually need to store in DB ->
#Builder
#Data
public class ProductResponse {
private Integer goodScore;
private Integer invalidScore;
private Float income;
private Double salary;
private LocalDate updatedOn;
}
And this is how I have tried and implemented ->
public class ProductImplement {
public static void main(String[] args) {
ProductRequest request = new ProductRequest();
try {
ProductResponse.builder()
.goodScore(!StringUtils.hasLength(request.getGoodScore()) ? Integer.parseInt(request.getGoodScore())
: null)
.income(!StringUtils.hasLength(request.getIncome()) ? Float.parseFloat(request.getIncome()) : null)
.invalidScore(
!StringUtils.hasLength(request.getInvalidScore()) ? Integer.parseInt(request.getInvalidScore())
: null)
.salary(!StringUtils.hasLength(request.getSalary()) ? Double.parseDouble(request.getSalary()) : null)
.updatedOn(
!StringUtils.hasLength(request.getUpdatedOn()) ? LocalDate.parse(request.getUpdatedOn()) : null)
.build();
}catch(Exception e) {
e.printStackTrace();
}
}
}
So, if the value is not Null I parse the type and set. Otherwise I set the field value to Null.
But, in this case if any exception occurs while parsing, the whole object returns Null and it is hectic to do this for morethan 200 fields.
Is there any framework
to validate individual data types and even in exception case we need to ignore that field and continue parsing for other fields? It is ok if I don't have to use Respone POJO. Any suggetsions are welcomed.
Please suggest. Thanks in Advance!
You can make use of #NotNull, #NotBlank , #MinLength, #MaxLength etc. from
javax.validation APIs
To ensure the validation, make use of #Validated at Controller level and #Valid at property level !
Attaching an article for reference!
https://www.baeldung.com/spring-valid-vs-validated
Difference between #Valid and #Validated in Spring
These will avoid manual validations and henceforth removing boilerplate code :)

Spring Webflux - WebClient: How to get a List<TheNestedPojo> nested inside a larger Response directly?

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

Kotlin: Change the json property name depending on the #JsonView

I am trying to use Jackson to serialize the same DTO object in 2 different ways, depending on the #JsonView.
I want to use 2 different names for the same field. In one case I want to name the json property myField (just like the class field name), in the other I want it to be named myInternalApiField.
As a result I would like to see outcomes similar to the presented below:
Usage 1 (External API View):
{
"myField": "value1",
"myOtherField": "otherValue"
}
Usage 2 (Internal API View):
{
"myInternalApiField": "value1",
"myOtherField": "otherValue"
}
In my implementation in Java to achieve that I used the combination of custom getters, setters and #JsonView annotation as below:
public class CustomDTO {
#JsonView(Views.ExternalApiView)
private String myField;
// Other fields here
#JsonView(Views.InternalApiView)
public String getMyInternalApiField() { return myField; }
#JsonView(Views.InternalApiView)
public void setMyInternalApiField(String value) { this.myField = value; }
#JsonView(Views.ExternalApiView)
public String getMyField() { return myField; }
#JsonView(Views.ExternalApiView)
public void setMyField(String value) { this.myField = value }
}
However I don't know how to properly achieve the same result in Kotlin.
I was thinking about using something like:
data class CustomDTO(
#get:[JsonView(Views.ExternalApiView) JsonProperty("myField")]
#get:[JsonView(Views.InternalApiView) JsonProperty("myInternalApiField")]
#set:[JsonView(Views.InternalApiView) JsonProperty("myField")]
#set:[JsonView(Views.InternalApiView) JsonProperty("myInternalApiField")]
var myField: String,
val myOtherField: String,
val myDifferentField: String
)
But this is not allowed in Kotlin.
Do you have any suggestions how to utilize the #JsonView in Kotlin in the similar way as I did it in Java?
How about something like:
data class CustomDTO(
#JsonView(ExternalApiView::class)
var myField: String,
val myOtherField: String,
val myDifferentField: String
) {
val myExternalField: String
#JsonView(InternalApiView::class)
get() {
return myField
}
}
It looks like there are ways that don't require creating computed properties in the DTO, like:
Using Jackson Mixins
Creating a custom serializer for a particular invocation
Combining a custom serializer with custom annotations
But these have their own complexity, even if that complexity isn't in the DTO class. I'm not sure these are much more appealing to me but you could see if they appeal to you.

How to generate an example POJO from Swagger ApiModelProperty annotations?

We are creating a REST API which is documented using Swagger's #ApiModelProperty annotations. I am writing end-to-end tests for the API, and I need to generate the JSON body for some of the requests. Assume I need to post the following JSON to an endpoint:
{ "name": "dan", "age": "33" }
So far I created a separate class containing all the necessary properties and which can be serialized to JSON using Jackson:
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyPostRequest {
private String name;
private String age;
// getters and fluid setters omitted...
public static MyPostRequest getExample() {
return new MyPostRequest().setName("dan").setAge("33");
}
}
However, we noticed that we already have a very similar class in the codebase which defines the model that the API accepts. In this model class, the example values for each property are already defined in #ApiModelProperty:
#ApiModel(value = "MyAPIModel")
public class MyAPIModel extends AbstractModel {
#ApiModelProperty(required = true, example = "dan")
private String name;
#ApiModelProperty(required = true, example = "33")
private String age;
}
Is there a simple way to generate an instance of MyAPIModel filled with the example values for each property? Note: I need to be able to modify single properties in my end-to-end test before converting to JSON in order to test different edge cases. Therefore it is not sufficient to generate the example JSON directly.
Essentially, can I write a static method getExample() on MyAPIModel (or even better on the base class AbstractModel) which returns an example instance of MyAPIModel as specified in the Swagger annotations?
This does not seem to be possible as of the time of this answer. The closest possibilities I found are:
io.swagger.converter.ModelConverters: The method read() creates Model objects, but the example member in those models is null. The examples are present in the properties member in String form (taken directly from the APIModelParameter annotations).
io.swagger.codegen.examples.ExampleGenerator: The method resolveModelToExample() takes the output from ModelConverters.read(), and generates a Map representing the object with its properties (while also parsing non-string properties such as nested models). This method is used for serializing to JSON. Unfortunately, resolveModelToExample() is private. If it were publicly accessible, code to generate a model default for an annotated Swagger API model class might look like this:
protected <T extends AbstractModel> T getModelExample(Class<T> clazz) {
// Get the swagger model instance including properties list with examples
Map<String,Model> models = ModelConverters.getInstance().read(clazz);
// Parse non-string example values into proper objects, and compile a map of properties representing an example object
ExampleGenerator eg = new ExampleGenerator(models);
Object resolved = eg.resolveModelToExample(clazz.getSimpleName(), null, new HashSet<String>());
if (!(resolved instanceof Map<?,?>)) {
// Model is not an instance of io.swagger.models.ModelImpl, and therefore no example can be resolved
return null;
}
T result = clazz.newInstance();
BeanUtils.populate(result, (Map<?,?>) resolved);
return result;
}
Since in our case all we need are String, boolean and int properties, there is at least the possibility to parse the annotations ourselves in a crazy hackish manner:
protected <T extends MyModelBaseClass> T getModelExample(Class<T> clazz) {
try {
T result = clazz.newInstance();
for(Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(ApiModelProperty.class)) {
String exampleValue = field.getAnnotation(ApiModelProperty.class).example();
if (exampleValue != null) {
boolean accessible = field.isAccessible();
field.setAccessible(true);
setField(result, field, exampleValue);
field.setAccessible(accessible);
}
}
}
return result;
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException("Could not create model example", e);
}
}
private <T extends MyModelBaseClass> void setField(T model, Field field, String value) throws IllegalArgumentException, IllegalAccessException {
Class<?> type = field.getType();
LOGGER.info(type.toString());
if (String.class.equals(type)) {
field.set(model, value);
} else if (Boolean.TYPE.equals(type) || Boolean.class.equals(type)) {
field.set(model, Boolean.parseBoolean(value));
} else if (Integer.TYPE.equals(type) || Integer.class.equals(type)) {
field.set(model, Integer.parseInt(value));
}
}
I might open an Issue / PR on Github later to propose adding functionality to Swagger. I am very surprised that nobody else has seemed to request this feature, given that our use case of sending exemplary model instances to the API as a test should be common.

Extract annotation parameters from a bean/class

I am using the #JsonProperty(name = "property_name") (Jackson) annotation wherever the property name in the json is different from the property name in my object. Is there a way I can programmatically access this information somewhere else in code?
Example:
public class Entity {
protected long entityName;
#JsonProperty("entity_name")
public long getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
}
What I need is a method to map entity_name to entityName. e.g, getActualFieldName("entity_name") should return "entityName". I can keep a separate file with all these mappings, but I don't want to do that because this information is already present in the form of #JsonProperty annotations. If I can extract it from there somehow, it would simplify things a bit.
Check this Helper utility. getAnnotationParameter

Categories

Resources