62

I have created a simple REST service (POST). But when i call this service from postman @RequestBody is not receiving any values.

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class Add_Policy {
    @ResponseBody
    @RequestMapping(value = "/Add_Policy", headers = {
            "content-type=application/json" }, consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    public Policy GetIPCountry( @RequestBody Policy policy) {

        System.out.println("Check value: " + policy.getPolicyNumber());
        return policy;

    }


}

My java Bean object is like below:

public class Policy {
    private String PolicyNumber;
    private String Type;
    private String Tenture;
    private String SDate;
    private String HName;
    private String Age;

    public String getPolicyNumber() {
        return PolicyNumber;
    }

    public void setPolicyNumber(String policyNumber) {
        PolicyNumber = policyNumber;
    }

    public String getType() {
        return Type;
    }

    public void setType(String type) {
        Type = type;
    }

    public String getTenture() {
        return Tenture;
    }

System.out.println is printing a null as a value for PolicyNumber.

Please help me to resolve this issue.

JSON which i am passing in request body is

{
    "PolicyNumber": "123",
    "Type": "Test",
    "Tenture": "10",
    "SDate": "10-July-2016",
    "HName": "Test User",
    "Age": "10"
}

I have even set Content-Type to application/json in postman

Geek
  • 1,214
  • 5
  • 14
  • 27
  • 2
    Apply `@ResponseBody` to the output of the method not the method itself. Also include the `produces` header value if you're expecting JSON value. – 11thdimension Aug 13 '16 at 19:00
  • Even if i make the response as void, values from the request is same null – Geek Aug 13 '16 at 19:03
  • `policy` itself wasn't null, are you sure that it contains `policyNumber` ? – 11thdimension Aug 13 '16 at 19:04
  • All the values in the `Policy` object is revived as null. I have added a `tostring()` method `policy` bean and checked this. – Geek Aug 13 '16 at 19:05
  • please could you show us your json request? – Pau Aug 13 '16 at 21:20
  • Try setting the first character of the properties in your JSON to lower case. Eg. { "policyNumber": "123", "type": "Test", "tenture": "10", "sDate": "10-July-2016", "hName": "Test User", "age": "10" } – AmanSinghal Aug 14 '16 at 06:29
  • Thanks @AmanSinghal it worked.. I changed all the keys' letters to lowercase. even `HName` to `hname`. But really dint understood this behavior of spring. – Geek Aug 14 '16 at 06:33
  • You need to follow camel case convention, setting name of all the properties in JSON would not help. – AmanSinghal Aug 14 '16 at 06:40

17 Answers17

105

Check the @RequestBody import,

wrong that will cause the problem in most cases.

import io.swagger.v3.oas.annotations.parameters.RequestBody;

to solve problem It should be

import org.springframework.web.bind.annotation.RequestBody;
Arshad Ali
  • 3,082
  • 12
  • 56
  • 99
vedavyasa k
  • 1,173
  • 1
  • 7
  • 4
81

Try setting the first character of the properties in your JSON to lower case. Eg.

{
    "policyNumber": "123",
    "type": "Test",
    "tenture": "10",
    "sDate": "10-July-2016",
    "hName": "Test User",
    "age": "10"
}

Basically, Spring uses getter and setter to set the properties of the the bean object. And it takes the property of the JSON object, matches it with the setter of the same name. eg to set the policyNumber property it tries to find a setter with the name setpolicyNumber() in your bean class and use that to set the value of your bean object.

AmanSinghal
  • 2,404
  • 21
  • 22
  • 5
    I had this problem because I forget to create getter and setter. – mahsa Oct 08 '19 at 10:26
  • 3
    i still get that issue. My properties are all lowercase. It gets the object but with all nulls like that ```Task{id=0, teachingHours=null, surveillanceHours=null, proofReading=null, isActive=false, isValidated=false, candidateId=null, supervisorId=null}``` – Panagiss Dec 31 '20 at 17:40
  • This might help: https://stackoverflow.com/a/76879877/9172548 – mr-possible Aug 10 '23 at 23:25
14

Setter would have been missed. So, Object values do not get set.

8

Java convention demands the name of variable in a POJO (attribute of a class) must to be the first character in lowercase.

You have uppercase letters in your JSON properties, which is what is causing the failure.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Adriano Dib
  • 91
  • 1
  • 3
8

If you are not in power to change the JSON format and still want to fix this problem, try adding @JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class) annotation before your DTO (Policy in example) class.

ubuiestubi
  • 81
  • 1
  • 1
3

I had lombok in my pom, and lombok annotations on my bean. I did not properly installed lombok with my STS yet, and had similar issue, my bean was not populated.

When I removed lombok annotations, my bean was properly populated.

Seems like a combination of lomboc not properly installed on STS + lomboc annotations on my bean.

Manu
  • 629
  • 7
  • 6
3

see spring PropertyNamingStrategy(UPPER_CAMEL_CASE,LOWER_CAMEL_CASE ,LOWER_CASE etc... defalult SNAKE_CASE). Spring will auto change http contorller class parameter by naming strategy, which may be not consistant with your request json take SNAKE_CASE as a ex, when "myToken" in java controller class, you client should send my_token instead of myToken

hu zhang
  • 31
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 06 '21 at 04:28
2

if you are using Lombok Api then there are no Getters and Setters publicly visible or available to the @ResponseBody and @RequestBody annotation. That is why we read the JSON request with null values.

So you need to comment those @Getter, @Setter annotation to Receive JSON response and Read JSON request object and generate the same getters and setters. Restart or Hot Load (using Spring-Boot-Devtools) server and it should work for sure. You can still use your lombok api for other Entities or BO's.

1

Use the annotation org.springframework.web.bind.annotation.RequestBody and not org.springframework.web.bind.annotation.ResponseBody

Jorge Moraleda
  • 362
  • 3
  • 8
1

In my case was a Lombok issue. I removed all the lombok annotations and created the constructor, setter and getter manually.

As an advise, I would also set the JSON to lowercase to follow the convention.

tufac2
  • 668
  • 6
  • 7
1

Apart from lowerCamelCasing, for me what additionally needed was applying @JsonProperty(value="your expected JSON KEY name") for each of the getter and setter methods and using this operator under the POJO/Bean/DTO class.

Sample Code:

@JsonProperty(value="policyNumber")
public void setPolicyNumber(String policyNumber) {
        this.policyNumber = policyNumber;
 }
TriS
  • 3,668
  • 3
  • 11
  • 25
Aatif
  • 11
  • 3
1

If you are using Lombok you need compileOnly and annotationProcessor In my case I missed the 2nd one. So I got all null values

compileOnly 'org.projectlombok:lombok:1.18.24'
annotationProcessor 'org.projectlombok:lombok:1.18.24'
ARods
  • 441
  • 2
  • 5
  • 13
0

In my case, empty constructor must be defined.

public MyClass(){}
AndroidDev
  • 39
  • 1
  • 7
0

Had the same issue but for my case only one field was not being set. A log on the request body object showed it was being recieved as null. deleted getters and setters for the field and autogenerated them using the IDE and all worked fine.

I highly suspect a mismatch in the getter and setter definition can also cause this

Austine Gwa
  • 804
  • 1
  • 9
  • 18
0

I have been having this issue too, but the best way i solve mine was checking on spaces after the first quotes in every initialization of fields in my json values

LAKIAR
  • 1
  • 2
0

1-Make Entity class properties start with lowercase. 2-Check for Annotations. 3-Check for Constructor--> **Entity classes should have two constructor. 4-Check for Getter and Setters.

beton
  • 29
  • 6
-1

In my case, date format was given incorrectly

Master Mind
  • 2,386
  • 3
  • 31
  • 48