Kalpak Gadre
Kalpak Gadre

Reputation: 6475

Spring DataBinder equivalent for Json

I am currently working on a web project which is using Play Framework 2.1.0. Play supports a decent API for parsing form data and mapping that to the Model beans directly. Which looks something like,

Form<Employee> form = Form.form(Employee.class).bindFromRequest();
if (form.hasErrors()) {
    return badRequest(template.render(form));
}

This API also does validations on the fly and is capable of handling binding failures, when say a String could not be converted to an Integer. The Form API keeps the collection of errors mapped to the name of the property. Underlying the Form API, Play is using DataBinder of Spring's validation framework which is actually doing all the magic.

I was wondering if there is similar binding API to convert from JSON to the bean directly, with support for handling binding failures?

Play 2.0 uses Jackson internally which fails when there are binding failures and simply throws an exception. I looked at the code and does not look easy to supress these errors.

Is there some framework that can satisfy my requirement out of the box?

Essentially, I need the framework to convert from JSON to Java Bean, which can handle binding failures gracefully.

It would be wonderful if it allows me to collect them somewhere so I can generate appropriate validation errors. I will run custom validations on the parsed object using javax.validation APIs to perform more specific validations once the JSON is parsed into the Bean.

Upvotes: 1

Views: 978

Answers (1)

Kalpak Gadre
Kalpak Gadre

Reputation: 6475

I achieved this by adding custom deserializers in Jackson

SimpleDeserializers deserializers = new SimpleDeserializers();

deserializers.addDeserializer(Integer.class, new MyIntegerDeserializer(null));
deserializers.addDeserializer(Long.class, new MyLongDeserializer(null));

ObjectMapper mapper = new ObjectMapper().setDeserializerProvider(
            new StdDeserializerProvider().withAdditionalDeserializers(deserializers));

MyModel value = mapper.treeToValue(node, MyModel.class);

MyIntegerDeserializer and MyLongDeserializer are custom deserializers for Integer and Long values respectively. These are in my case exact copy of the internal default corresponding deserializer classes with additional code to gracefully handle NumberFormatException

Upvotes: 1

Related Questions