Salman Shaikh
Salman Shaikh

Reputation: 595

Jersey sets value of POJO to 0

I am using Jersey 2.x

I have following POJO class with setters and getters.

public class AccountObject {

private int accountNumber;
private int accountStatus;

//Getters and Setters

}

This is my method signature in Controller

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("application/json")
    public Response createAccount(AccountObject accountObject, @Context ContainerRequestContext requestContext) {

//

}  

I am calling my API with the empty JSON body

{}

Problem is : I am getting accountNumber and accoutStatus values as 0

I have written some validation functions to check accountNumber and accountStatus , so because of this behaviour , my function is bypassed.

I am unable to understand how the values are assigned to value 0

Upvotes: 1

Views: 272

Answers (2)

Sabir Khan
Sabir Khan

Reputation: 10142

This has nothing to do with Jersey but with Core Java & Jackson rules.

Jersey uses Jackson to handle POJO based JSON binding support as mentioned here

so you have to understand how Jackson works when it receives and Empty JSON like below,

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class App 
{
    public static void main( String[] args ) throws JsonParseException, JsonMappingException, IOException
    {

        String JSON = "{}";

        ObjectMapper mapper = new ObjectMapper();

        AccountObject acObject = mapper.readValue(JSON, AccountObject.class);

        System.out.println(acObject.getAccountNumber()+" :"+acObject.getAccountStatus());


    }
}

You will see that Jackson creates an AccountObject with default int primitive value as zero ( as per core Java rules ) , since it doesn't find any value in Input JSON.

If you change field types to Integer then those values will become null as per Core Java default field rules.

int is not a reference type so it can't be assigned to null .

So you need to change your POJO as per your validation requirements or change your validation logic as per your POJO.

Just for the sake of completeness , dependencies as below ,

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

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

Upvotes: 2

itsmichaelwang
itsmichaelwang

Reputation: 2328

If you want it to be null, try using Integer instead of int. An int cannot be null because it is a primitive type, but an Integer can.'

docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

Upvotes: 1

Related Questions