Home » Java » java – How to Handle 500 internal error while mapping JSON to POJO If one of attribute of POJO class is empty-Exceptionshub

java – How to Handle 500 internal error while mapping JSON to POJO If one of attribute of POJO class is empty-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hi I am working on Rest API written in java and have come through the below doubt.

I have already written the code which takes post data and maps to pojo class and sends back the data in JSON form.

Correct Format:-

{
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}

Output:

{
    "Pkid":"1",
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}

But when I am passing empty value to one of the attribute I am getting 500 internal error can someone help me how to handle it and return the value in json format after handling it:

{
    "Name":,
    "Address":"Mumbai",
    "Age": 27
}

Output:

500 Internal error
How to&Answers:

You can use Jackson library and set the below property while creating object.

val mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Add the below maven dependency :

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.7</version>
        </dependency>

You can see the answer here also.

EDIT 1:
Deserialize your jsonObject as :

objectMapper.readValue(jsonString,POJO.class)

Answer:

first of all, use a json validator. it seems that you have a missing comma.

https://jsonformatter.curiousconcept.com/

And also it is helpful to share corresponding code, and retrieved exception etc.

Answer:

Understanding: you are trying to store an object and return the object details along with the primary key id generated
Following are two approaches for this:

1. Custom de-serializer with Jackson:
I would prefer this method because it provides you with additional security. In the current scenario, you are exposed to cross-site scripting attacks
Using a custom de-serializer along with Jsoup api or Antisamy to filter the data would help you prevent XSS and also include null values.

You need to add your custom de-serializer to your pojo using:

    @JsonDeserialize(using = CustomDeserializer.class)
    public class User {
       private String id;

       private String name;
      // standard getters and setters
    }

2. Using Jackson annotation:

public class User {

    @JsonInclude(Include.NON_NULL)
    private String id;

    private String name;

    // standard getters and setters
}