So basically, I have JSON payload that I want to deserialize into an custom object. To do this I'm using JacksonDeserializer. I'm also using Spring Validation Annotations to validate fields. Is there a way I get to the Spring Validation inside the deserializer so I can return appropriate exceptions/errors.
Related
I`m using Play Framework 1.5 and I'm new in this framework. How can I retrieve the body as JSON when i sent a request body with JSON:
{
"inputNo": 111111,
"name": "検証 太郎"
}
AFAIK there is no built in JSON binding support in Play1x. You can implement binding process manually by using #Before annotation in controller class. In the #Before annotated method, get the json from request body (params.get("body")), parse it using GSON or any other JSON library, and store the pojo in the request object (request.args.put(name, pojo)). Later in the controller method get the pojo from request args (request.args.get(name)). You can define custom annotations to limit this behaviour.
A good implementation would be creating a base controller class with #Before annotation and making this process generic using types.
I am using return ResponseEntity of Spring to return HTTP response.
While passing POJO or MAP in entity, it converts that to JSON Object. Like
return new ResponseEntity<Object>(result, HttpStatus.OK);
result may be POJO class. (getter and setters)
I am using
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.GsonHttpMessageConverter ">
</bean>
Now what i want is, i will get a list of response fields in request. I just want to response the request with those fields only.
For Ex, if i receive the response fields as name,id. Then the object must contain those two only.
{
"name":"test",
"id":15
}
i can't able to use #jsonignore or #explore annotations. B'Coz i want the JSON to be done dynamically using coding.
May be by overriding the GSON convertor methods or using AOP.
Is there any way to configure the adapter of jackson to create the object based on the fields.
If you can switch to jackson probably you can use this little extension i wrote for exactly this purpose:
https://github.com/Antibrumm/jackson-antpathfilter
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.
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
Are there any online tutorial available to use Hibernate validator with Jackson for validating JSON?
I am using Spring and Jackson now for JSON parsing.
With Spring, I use MappingJacksonHttpMessageConverter to automatically translate the incoming JSON payload to Java object.
I would like to add validator annotations to the Java class. For example, if I have the Person class with "name" as one of the fields, I like to validate the JSON payload if the "name" element appears 1 time. If it appears more than 1 time in the payload, then I like the validator to kick in to reject the request.
Right now what I observed is that if there are multiple names in the payload, Jackson simply ignores and picks up the last one.
The Java object is not bound to any XML schema and the like.
What is the best practice for validating JSON?
Spring has JSR-303 support built in, see this chapter in the reference manual.
If you are using Spring MVC, see here, you should just be able to annotate parameters to #RequestMapping methods with #Valid.
I have a request(POST or GET), having one variable "data" (coming from Xcode)
now data have assigned JSON object
data={"method":"Auth","action":"login"}
now I have a bean having exactly these two fields(i.e. method,action)
now in Spring controller I have method "login".
I want this method to be invoked based on value in "action" of the request JSON object.
Now, I'm not getting what exactly types of annotation i should use.
Please help..
You need to add Jackson to the classpath, and add <mvc:annotation-driven> to your Spring context, then Spring will automatically register a MappingJacksonHttpMessageConverter for JSON Objects.
Now Annotate your method like this:
#ResponseBody
#RequestMapping("/some/path")
public YourResponseObject someName(#RequestBody YourRequestObject data){
// do something here
}
(Both YourRequestObject and YourResponseObject will be automatically converted to and from JSON, but this works only for POST requests AFAIK)