Ke Liu Ke Liu - 1 year ago 69
Java Question

Why not make some methods in com.fasterxml.jackson.databind.ObjectMapper static?

In my project i used a lot com.fasterxml.jackson.databind.ObjectMapper to deal with JSON, for example:

ObjectMapper mapper = new ObjectMapper();
A a = mapper.readValue(file.getBytes(), A.class);

At first sight I think it's better it's better to make the readValue method static, then we can use it as ObjectMapper.readValue(), much more clear. But I know there must be some reasons that it shouldn't, does anyone know it?

Answer Source

Other reason is with each instance of ObjectMapper you bind certain specific confuguration ready by ObjectMapper while serialization and desrialization process somethinglike below. So you can configure different startegies while object conversion process.

 ObjectMapper mapper = new ObjectMapper();
   mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
   String json = mapper.writeValueAsString(new MyBean());