How can I tell jackson to ignore a property for which I don't have control over the source code?
You can use Jackson Mixins. For example:
class YourClass {
public int ignoreThis() { return 0; }
}
With this Mixin
abstract class MixIn {
@JsonIgnore abstract int ignoreThis(); // we don't need it!
}
With this:
objectMapper.getSerializationConfig().addMixInAnnotations(YourClass.class, MixIn.class);
Edit:
Thanks to the comments, with Jackson 2.5+, the API has changed and should be called with objectMapper.addMixIn(Class<?> target, Class<?> mixinSource)
Ignore specific field on serialization with Jackson
Ok, so for some reason I missed this answer.
The following code works as expected:
@JsonIgnoreProperties({"foobar"})
public static class Foo {
public String foo = "a";
public String bar = "b";
public String foobar = "c";
}
//Test code
ObjectMapper mapper = new ObjectMapper();
Foo foo = new Foo();
foo.foobar = "foobar";
foo.foo = "Foo";
String out = mapper.writeValueAsString(foo);
Foo f = mapper.readValue(out, Foo.class);
Can I ignore a getter-based write-only property during deserialization in Java Jackson?
Jackson supports "one-way" properties using the access
parameter of @JsonProperty
. Annotate your property like this:
@JsonProperty(access = READ_ONLY)
public boolean isLegacyValue() {
return true;
}
How to tell Jackson to ignore a field during serialization if its value is null?
To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper
directly, or make use of the @JsonInclude
annotation:
mapper.setSerializationInclusion(Include.NON_NULL);
or:
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Alternatively, you could use @JsonInclude
in a getter so that the attribute would be shown if the value is not null.
A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.
Jackson serialization: how to ignore superclass properties
You can register a custom Jackson annotation intropector which would ignore all the properties that come from the certain super type. Here is an example:
public class JacksonIgnoreInherited {
public static class Base {
public final String field1;
public Base(final String field1) {
this.field1 = field1;
}
}
public static class Bean extends Base {
public final String field2;
public Bean(final String field1, final String field2) {
super(field1);
this.field2 = field2;
}
}
private static class IgnoreInheritedIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(final AnnotatedMember m) {
return m.getDeclaringClass() == Base.class || super.hasIgnoreMarker(m);
}
}
public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new IgnoreInheritedIntrospector());
final Bean bean = new Bean("a", "b");
System.out.println(mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(bean));
}
}
Output:
{
"field2" : "b"
}
Safely Ignore JSON Property that Contains All Other Objects
There are 2 possibilities:
1) create variable grouping
and parse result as object:
For example:
ObjectMapper mapper = new ObjectMapper();
Holder holder = mapper.readValue(content, Holder.class);
ObjHolder[] objHolder = holder.getGrouping().getObjHolderArray();
2) read whole JSON as JsonNode, navigate to grouping
and parse it's content to array. For example:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(content);
JsonNode array = actualObj.get("grouping");
ObjHolder[] objHolders = mapper.treeToValue(array, ObjHolder[].class);
Jackson read-only property in method
You can use JsonIgnoreProperties
annotation:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.ThreadLocalRandom;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
Configuracao c = new Configuracao();
c.setDepartamento("D1");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(c);
System.out.println(json);
System.out.println(mapper.readValue(json, Configuracao.class));
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Configuracao {
private String departamento;
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
public String getDepartamentos() {
return departamento + " " + ThreadLocalRandom.current().nextDouble();
}
@Override
public String toString() {
return "Configuracao{" +
"departamento='" + departamento + '\'' +
'}';
}
}
Above code prints:
{"departamento":"D1","departamentos":"D1 0.8600092703789755"}
Configuracao{departamento='D1'}
JsonProperty.Access.READ_ONLY
should also works:
class Configuracao {
private String departamento;
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getDepartamentos() {
return departamento + " " + ThreadLocalRandom.current().nextDouble();
}
@Override
public String toString() {
return "Configuracao{" +
"departamento='" + departamento + '\'' +
'}';
}
}
with above test works as expected.
If you have more classes like this and fields to ignore, you can disable globally feature DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Everything was tested with version 2.9.9
Related Topics
Java: Join Array of Primitives with Separator
Parsing JSON with Gson, Object Sometimes Contains List Sometimes Contains Object
Differencebetween 'Super' and 'Extends' in Java Generics
Get Cell Value from Excel Sheet with Apache Poi
Is the Java Hashmap Keyset() Iteration Order Consistent
What Is Better: Multiple "If" Statements or One "If" with Multiple Conditions
Understanding Logic in Caseinsensitivecomparator
How to Get Unique Values from Array
Chromedriver and Webdriver for Selenium Through Testng Results in 4 Errors
How to Get the Session Object If I Have the Entity-Manager
No Dialect Mapping for Jdbc Type: 1111
How to Define Multiple Jbutton Actions from a Different Class
How to Read Properties File in Web Application
Getting the Name of a Method Parameter
"The Public Type <<Classname>> Must Be Defined in Its Own File" Error in Eclipse