how to automatically recognize which class the jsonnode should be converted to? - jackson

I have two custom java objects
public class myClass1{
JsonNode header;
JsonNode body;
···
}
public class myClass2{
JsonNode header;
ArrayNode body;
···
}
I know I can convert the jsonnode to an object like this
ObjectMapper mapper = new ObjectMapper();
myClass1 myNode = mapper.treeToValue(myJsonNode, myClass1.class);
But what if I don't know which class it should be converted to? How can I let it automatically recognize which class it should be converted to?

Related

Jackson - mapping OffsetDateTime [duplicate]

I have problems LocalDateTime deserialization in Junit test. I have simple REST API which returns some DTO object. When I call my endpoint there is no problem with response - it is correct. Then I try to write unit test, obtain MvcResult and with use of ObjectMapper convert it to my DTO object. But I still receive:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.time.LocalDateTime` out of START_ARRAY token
at [Source: (String)"{"name":"Test name","firstDate":[2019,3,11,18,34,43,52217600],"secondDate":[2019,3,11,19,34,43,54219000]}"; line: 1, column: 33] (through reference chain: com.mylocaldatetimeexample.MyDto["firstDate"])
I was trying with #JsonFormat and adding compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8' to my build.gradle but I use Spring Boot 2.1.3.RELEASE so it is involved in it. I do not have any idea how to fix it. My simple endpoint and unit test below:
#RestController
#RequestMapping("/api/myexample")
public class MyController {
#GetMapping("{id}")
public ResponseEntity<MyDto> findById(#PathVariable Long id) {
MyDto myDto = new MyDto("Test name", LocalDateTime.now(), LocalDateTime.now().plusHours(1));
return ResponseEntity.ok(myDto);
}
}
MyDto class
public class MyDto {
private String name;
private LocalDateTime firstDate;
private LocalDateTime secondDate;
// constructors, getters, setters
}
Unit test
public class MyControllerTest {
#Test
public void getMethod() throws Exception {
MyController controller = new MyController();
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/myexample/1"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
String json = mvcResult.getResponse().getContentAsString();
MyDto dto = new ObjectMapper().readValue(json, MyDto.class);
assertEquals("name", dto.getName());
}
}
You create new ObjectMapper in test class:
MyDto dto = new ObjectMapper().readValue(json, MyDto.class);
Try to inject ObjectMapper from Spring context or manually register module:
mapper.registerModule(new JavaTimeModule());
See also:
jackson-modules-java8

Manually convert JSON to Object using Spring Data Rest

Let's say I have the following entity:
public class Employee {
private String name;
private Company company
}
And I have a String with the content below:
{
"name":"Joe",
"company": "http://localhost/companies/23"
}
Spring Data Rest is capable of converting this JSON to an Employee object out of the box, but to how convert it manually?
OK. I think I understand the problem now. Of course SDR has to have an ObjectMapper which is capable to convert the incoming JSON into an entity (including hateoas links), but it seems that's NOT the default ObjectMapper and it's not even exported as a Bean.
So I made some reverse-engineering and I think I've found what you need. Fortunately the ObjectMapper which is used internally has a public getter in the RepositoryRestMvcConfiguration class, so it can be used easily:
/**
* The Jackson {#link ObjectMapper} used internally.
*
* #return
*/
public ObjectMapper objectMapper() {
return mapper.get();
}
I think the following code will work:
#Autowired
RepositoryRestMvcConfiguration rrmc;
private <T> T readValue(String json, Class<T> type)
throws IOException, JsonParseException, JsonMappingException {
return rrmc.objectMapper().readValue(json, type);
}
#Aurowired
private final RepositoryInvokerFactory repositoryInvokerFactory;
private Object loadPropertyValue(Class<?> type, String href) {
String id = href.substring(href.lastIndexOf('/') + 1);
RepositoryInvoker invoker = repositoryInvokerFactory.getInvokerFor(type);
return invoker.invokeFindById(id).orElse(null);
}

Cannot deserialize java.time.Instant

I have a RestEasyClient that has to deserialize an object that has a java.time.Instant inside. I tried to register the new JavaTimeModule from jsr310 but still got errors:
ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
ResteasyClient client = new ResteasyClientBuilder()
.register(mapper)
.build();
ResteasyWebTarget target = client.target(UriBuilder.fromPath(SERVICE_URL + "/api"));
Error:
Can not construct instance of java.time.Instant: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
After modifying Rest Server to properly serialize the Instant class (ex: "fromTime": 1525681860)
New Error:
Can not construct instance of java.time.Instant: no double/Double-argument constructor/factory method to deserialize from Number value (1.52568186E9)
I managed to simulate this:
ObjectMapper deserializer = new ObjectMapper()
.registerModule(new JavaTimeModule());
Instant probe = deserializer.readValue("1525681860", Instant.class);
System.out.println(probe);
If I remove the "registerModule" line, I get the same error.
Therefore, the conclusion is that RestEasyClient not registering the module. I am definitely doing something wrong.
You could define a ContextResolver for ObjectMapper:
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
this.mapper = createObjectMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
}
And then register the resolver in your client instance:
ResteasyClient client = new ResteasyClientBuilder()
.register(ObjectMapperContextResolver.class).build();
Alternatively you could register an instance of JacksonJsonProvider. This class is the basic implementation of JAX-RS abstractions (MessageBodyReader and MessageBodyWriter) needed for binding JSON content to and from Java objects.
You can use the constructor that accepts an ObjectMapper instance.

Hibernate Validator and Jackson: Using the #JsonProperty value as the ConstraintViolation PropertyPath?

Say I have a simple POJO like below annotated with Jackson 2.1 and Hibernate Validator 4.3.1 annotations:
final public class Person {
#JsonProperty("nm")
#NotNull
final public String name;
public Person(String name) {
this.name = name;
}
}
And I send JSON like such to a web service:
{"name": null}
Hibernate when it reports the ConstraintViolation uses the class member identifier "name" instead of the JsonProperty annotation value. Does anyone know if it is possible to make the Hibernate Validator look at the annotation of the class and use that value instead?
Unfortunately there is no easy way to do it. But here are some insights that can help you:
Parsing constraint violations
From the ConstraintViolationException, you can get a set of ConstraintViolation, that exposes the constraint violation context:
ConstraintViolation#getLeafBean(): If it is a bean constraint, this method returns the bean instance in which the constraint is applied to.
ConstraintViolation#getPropertyPath(): Returns the path to the invalid property.
From the property path, you can get the leaf node:
Path propertyPath = constraintViolation.getPropertyPath();
Optional<Path.Node> leafNodeOptional =
StreamSupport.stream(propertyPath.spliterator(), false).reduce((a, b) -> b);
Then check if the type of the node is PROPERTY and get its name:
String nodeName = null;
if (leafNodeOptional.isPresent()) {
Path.Node leafNode = leafNodeOptional.get();
if (ElementKind.PROPERTY == leafNode.getKind()) {
nodeName = leafNode.getName();
}
}
Introspecting a class with Jackson
To get the available JSON properties from the leaf bean class, you can introspect it with Jackson (see this answer and this answer for further details):
Class<?> beanClass = constraintViolation.getLeafBean().getClass();
JavaType javaType = mapper.getTypeFactory().constructType(beanClass);
BeanDescription introspection = mapper.getSerializationConfig().introspect(javaType);
List<BeanPropertyDefinition> properties = introspection.findProperties();
Then filter the properties by comparing the leaf node name with the Field name from the BeanPropertyDefinition:
Optional<String> jsonProperty = properties.stream()
.filter(property -> nodeName.equals(property.getField().getName()))
.map(BeanPropertyDefinition::getName)
.findFirst();
Using JAX-RS?
With JAX-RS (if you are using it), you can define an ExceptionMapper to handle ConstraintViolationExceptions:
#Provider
public class ConstraintViolationExceptionMapper
implements ExceptionMapper<ConstraintViolationException> {
#Override
public Response toResponse(ConstraintViolationException exception) {
...
}
}
To use the ObjectMapper in your ExceptionMapper, you could provide a ContextResolver<T> for it:
#Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = createObjectMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
}
Inject the Providers interface in your ExceptionMapper:
#Context
private Providers providers;
Lookup for your ContextResolver<T> and then get the ObjectMapper instance:
ContextResolver<ObjectMapper> resolver =
providers.getContextResolver(ObjectMapper.class, MediaType.WILDCARD_TYPE);
ObjectMapper mapper = resolver.getContext(ObjectMapper.class);
If you are interested in getting #XxxParam names, refer to this answer.
No, that's not possible. Hibernate Validator 5 (Bean Validation 1.1) has the notion of ParameterNameProviders which return the names to reported in case method parameter constraints are violated but there is nothing comparable for property constraints.
I have raised this issue as I am using problem-spring-web module to do the validation, and that doesn't support bean definition names out of box as hibernate. so I have came up with the below logic to override the createViolation of ConstraintViolationAdviceTrait and fetch the JSONProperty field name for the field and create violations again.
public class CustomBeanValidationAdviceTrait implements ValidationAdviceTrait {
private final ObjectMapper objectMapper;
public CustomBeanValidationAdviceTrait(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
#Override
public Violation createViolation(ConstraintViolation violation) {
String propertyName = getPropertyName(violation.getRootBeanClass(), violation.getPropertyPath().toString());
return new Violation(this.formatFieldName(propertyName), violation.getMessage());
}
private String getPropertyName(Class clazz, String defaultName) {
JavaType type = objectMapper.constructType(clazz);
BeanDescription desc = objectMapper.getSerializationConfig().introspect(type);
return desc.findProperties()
.stream()
.filter(prop -> prop.getInternalName().equals(defaultName))
.map(BeanPropertyDefinition::getName)
.findFirst()
.orElse(defaultName);
}

How to define string name as class in java

I am using Jackson parser for JSON parsing in android app. The JSON data is in following form
data: {
train_number: "12951",
chart_prepared: false,
class: "2A"
}
How to parse property with class name in Java?
Please, help me.
At the beginning - your JSON is not valid. It should look like this:
{"train_number":1,"chart_prepared":false,"class":"2A"}
You can change default name property using #JsonProperty annotation.
Your POJO class should looks like that:
class Data {
private int train_number;
private boolean chart_prepared;
#JsonProperty(value = "class")
private String clazz;
...
}
Now you can build simple test method:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
Data data = new Data();
data.setTrain_number(1);
data.setClazz("2A");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(data);
System.out.println(json);
System.out.println(objectMapper.readValue(json, Data.class));
}
}
Above program prints:
{"train_number":1,"chart_prepared":false,"class":"2A"}
Data [train_number=1, chart_prepared=false, clazz=2A]