Spring - Problem converting a pojo to a JSON (No converter found error)

1378 views java
5

spring 4.3.3

I'm trying to convert a Pojo to JSON, marking the Controller as a
@RestController, the problem with that is some elements are with first letter lower instead of upper case,

Ex:
"Id": 1, //This is ok  
"customerId": "1234", //Instead of CustomerId, this has customerId
...

Controller

@RestController
...
public class BOSIOrderController3 {
    ...
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public CustomerResponse postCustomerRequest(final HttpServletRequest request) { 

I want that to be in upper case. The pojo is basically a xjc generated class from an xsd, and it contains,

@XmlElement(name = "Id")
protected int id;
@XmlElement(name = "CustomerId")
protected String customerId;
...
    public int getId() {
        return id;
    }
    public void setId(int value) {
        this.id = value;
    }
    public String getCustomerId() {
        return customerId;
    }
    public void setCustomerId(String value) {
        this.customerId = value;
    }

This has associated setter, getter for each attributes. In the Controller, I got ObjectMapper case insensitive set to true as well,

mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); 

I also tried with, marking the Controller as @Controller instead of @RestController, provided @ResponseBody before the method,

Controller

@Controller
...
public class CustomerController {
...
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @ResponseBody
    public String postCustomerRequest(HttpServletRequest request) {
        ...

//Used PropertyNamingStrategy with the ObjectMapper, converted the first character to an upper case, 
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
            ...
            CustomerResponse response=createCustomer(document,objectFactory);
            mapperObj.setPropertyNamingStrategy(new CustomerJsonNameStrategy());
            String jsonOutput = mapperObj.writeValueAsString(response);
            return jsonOutput;

If I see the value of jsonOutput during debug in Eclipse, it outputs the json elements in correct case, but the response to the rest client is coming as,

{"errors": [{
   "message": "No converter found for return value of type: class java.lang.String",
   "type": "IllegalArgumentError"
}]}

Looks like the jackson serializier is interferring with the response and throwing the above error.

What's the solution for this?

answered question

1 Answer

11

Spring uses Jackson for converting POJO to json. Jackson by default makes first letter of field name small. If you wants custom names then add following jackson annotation.

@JsonProperty("CustomerId")
private String customerId; 

posted this

Have an answer?

JD

Please login first before posting an answer.