Aarkan
Aarkan

Reputation: 4109

Parsing JSON request body with Spring MVC

I am using Spring 4.1 framework for developing webservices. When I return a Java object as response, it is automatically converted to JSON and delivered to client, so I assume that JSON parser is in classpath and it is configured properly. However it fails to convert the request body from JSON into Java object and client is getting a HTTP response of 400.

Here is how the webservice looks like:

public class Details{
        public Details(){

        }
        int code;
        int area;
    }

@RequestMapping(value = "/api/update/{phoneNumber}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> update(@PathVariable final String phoneNumber, @RequestBody Details details)

Here is how the request looks like:

Method: Post
Content-Type: application/json; charset=utf-8
Body: {"code":0,"area":12}

If I collect the request body as string and parse it manually then it works, so it gets the valid JSON but for some reason it is not parsing it automatically. I have no clue on how to fix it. Please help. Thanks in advance.

Upvotes: 0

Views: 2544

Answers (2)

Aarkan
Aarkan

Reputation: 4109

Finally I got the reason for this. I was using inner classes which were not static. Making those static fixed the issue.

Upvotes: 1

Vladimir
Vladimir

Reputation: 9753

You have package-private properties in your Details class, so they are probably not recognised by json-converter.

You have several options:

  • define them as public (not recommended)
  • provide getters and setters
  • if you are using jackson, you can annotate them with @JsonProperty, leaving them package-private

Upvotes: 1

Related Questions