Spring Post Controller not Serializing JSON Request to Java Object

spring json serializer
custom json response spring boot
spring mvc serialize object to json
spring mvc deserialize json
spring responseentity serialization
serialization in spring mvc
spring model serialization
how to send json response from spring controller

So I have this controller:

@RequestMapping(value = "/zone/settings/ranged/update", method = RequestMethod.POST, produces="application/json", consumes="application/json")
public @ResponseBody ResponseEntity<Map<String, Object>> zoneSettingsRangedUpdate(
        WebRequest request,
        @RequestBody RoundRangeData data,
        Map<String, Object> model
) throws IOException {
    model.put("request", data);
    model.put("success",true);

    return new ResponseEntity<>(model, HttpStatus.OK);
}

With this as the POJO:

public class RoundRangeData {
    private BigInteger pricingDate;
    private Long zoneid;
    private Long psid;
    private Float roundTo;
    private Float lowerLimit;
    private Float upperLimit;

public RoundRangeData() {

}

public RoundRangeData(BigInteger pricingDate, Long zoneid, Long psid, Float roundTo, Float lowerLimit, Float upperLimit) {
    this.pricingDate = pricingDate;
    this.zoneid = zoneid;
    this.psid = psid;
    this.roundTo = roundTo;
    this.lowerLimit = lowerLimit;
    this.upperLimit = upperLimit;
}

public BigInteger getPricingDate() {
    return pricingDate;
}

public void setPricingDate(BigInteger pricingDate) {
    this.pricingDate = pricingDate;
}

public Long getZoneid() {
    return zoneid;
}

public void setZoneid(Long zoneId) {
    this.zoneid = zoneId;
}

public Long getPsid() {
    return psid;
}

public void setPsid(Long psid) {
    this.psid = psid;
}

public Float getRoundTo() {
    return roundTo;
}

public void setRoundTo(Float roundTo) {
    this.roundTo = roundTo;
}

public Float getLowerLimit() {
    return lowerLimit;
}

public void setLowerLimit(Float lowerLimit) {
    this.lowerLimit = lowerLimit;
}

public Float getUpperLimit() {
    return upperLimit;
}

public void setUpperLimit(Float upperLimit) {
    this.upperLimit = upperLimit;
}
}

Using this request (Chrome devtools screenshot, actual request has quotes around properties):

And I keep getting this error:

WARNING: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.validation.support.BindingAwareModelMap["org.springframework.validation.BindingResult.roundRangeData"]->org.springframework.validation.BeanPropertyBindingResult["messageCodesResolver"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.validation.support.BindingAwareModelMap["org.springframework.validation.BindingResult.roundRangeData"]->org.springframework.validation.BeanPropertyBindingResult["messageCodesResolver"])

What I have tried:

  • Changed field accessors to public
  • Tried digesting a normal string, same error
  • Annotated each getter with @JSONProperty
  • Created a unit test and called the controller using generated JSON from object mapper from an instance of the RoundRangeData Object

Serializing Java objects into JSON works for responses, but I'm having no luck serializing JSON into Java objects in my controllers.

You need to remove the attribute model from the parameter list. The problem if you enable FAIL_ON_EMPTY_BEANS for jackson, you will get a huge response back which contain a lot of information, which I am pretty sure you do not need.

I would return in the new ResponseEntity something else, like creating your own map, if that is your desire.

Spring MVC & JSON Serialization, In this posting I will show you how to customize json serialization in the context of the Spring MVC. The code is Below you find the BasketItem class and the Controller. BasketItem is used in request and response. I want to point out If you do not set that, then Spring does not invoke Jackson at all. Java. However, this results in our attribute named jsonData not being returned by our controller.. So how can we return an object that may be serialized to Json by Jackson. Using @JsonProperty annotation so that we have a method to convert our attribute to a Jackson friendly object.

Try this.

public class MapSerializer extends JsonSerializer<SpecialMap> {
    @Override
    public void serialize(SpecialMap map, JsonGenerator jgen,
                          SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        for (String key : map.keySet()) {
            jgen.writeStringField(key, map.get(key));
        }
        jgen.writeEndObject();
    }
}


public class SpecialMap extends HashMap<String,String> {
}


@RequestMapping(value = "/zone/settings/ranged/update", method = {RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> zoneSettingsRangedUpdate(
            @RequestBody RoundRangeData data
    ) throws IOException {

        Map<String, Object> model = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();

        SimpleModule module = new SimpleModule();
        module.addSerializer(SpecialMap.class, new MapSerializer());
        mapper.registerModule(module);

        String serialized = mapper.writeValueAsString(data);
       // return serialized;
        model.put("request", serialized);
        model.put("success",true);

        return new ResponseEntity<Map<String, Object>>(model, HttpStatus.OK);
    }

See the image of successful response.

Spring Rest:Jackson's JsonNode for Payload unaware request , Spring Rest:Jackson's JsonNode for Payload unaware request Handling a request which we need to send to the service then that has to be de-serialized to a Java object. And this has to be received at the Spring Controller method with annotation In this scenario,we may not require to know the request and response  In this article, We will learn how we can customize JSON Serialize and Deserialize in spring boot application. @JsonComponent is annotation using that we can customize the JSON request or response. Spring boot internally used Jackson library for Object to JSON conversion.

You only need to implement Serializble in your pojo

public class RoundRangeData implements Serializable {
    //code
}

Spring - Custom deserialization of JSON requests, Spring uses Jackson library to convert JSON requests to Java objects. I'll talk about customizing JSON request mapping in this post. "birth":1912, "alive":true } Suppose we have following POJO and controller: public class  The hybris eCommerce APIs support the JSON and XML response formats. While many clients to the API will prefer to work directly with low level JSON and XML Objects (e.g. JSONObject from org.json), some developers will of course prefer to work with deserialized Objects such as SearchResult, Product or Facet. For the purpose of this blog post, I quickly evaluated the Spring RestTemplate which

Spring MVC - Convert JSON Message to Object using , Spring provides support for JSON content-type to backing object conversion by public class User implements Serializable { private Long id; private String name; isCreated()); // create one more user builder = MockMvcRequestBuilders.post("​/users/register") . UserController Method = public java.util. Screencast #14: Post JSON to spring REST webservice. After making a GET request to a REST service the natural progression is to POST information back to the server. In this episode we will look at how to post json to spring controller and have it automatically convert JSON to arraylist, object or multiple objects.

Returning JSON object as response in Spring Boot when returning , When using Spring Boot @RestController, we are able to return directly however if using a JSONObject in our entity like in the last post However, this results in our attribute named jsonData not being returned by our controller. So how can we return an object that may be serialized to Json by Jackson. Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody. This annotation is applied to a class to mark it as a request handler. Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the

Introduction to Java Serialization, is the conversion of a Java object into a static stream (sequence) of bytes which can then be saved to a database or transferred over a network. The @Valid annotation makes sure that all the defined validations are executed (for example, the string name must not exceed 60 characters). Sending the Frontend Request. Our goal is to send a JSON encoded object with all the necessary parameters directly to the Spring Boot REST endpoint.

Comments
  • You can click on tab View Source to show the actual payload.
  • Do you need the Map<String, Object> model bit? Can you try removing it?
  • did you configure something on the default ObjectMapper or are using using some custom serialization configuration for it? might be something regarding serialization would fail if FAIL_ON_EMPTY_BEANS would be set to true
  • you need to remove that model, I think. The problem if you enable FAIL_ON_EMPTY_BEANS you will get a huge response back which contain a lot f information, which I am pretty sure you do not need. I would return in the new ResponseEntity something else, like creating your own map, if that is your desire, but I wouldn't use that. I think in order to use that model, you wll need to use @ModelMap or something like that
  • Holy crap, @sfat you're a genius, I removed the model from the arguments and it worked. No clue why.
  • It seems to be working now. Before hand I implemented a class that extended SimpleModule and just registered that, but I followed the general flow of your code snippet and it seems to be working. Thanks so much!