I have the following simple class:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties({ "thirdField" })
public class Message {
private TypeA type;
private String producer;
//Getters and Setters
}
in my test class
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public void testMethd() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.USE_ANNOTATIONS, true);
Class<T> instanceType = Message.class;
String msgBody = "{\"producer\": \"clientApp\", \"type\": \"aType\", \"thirdField\": []}";
objectMapper.readValue(msgBody, instanceType);
}
}
All I am trying to do is to convert the above json string into Message class and ignore the 'thirdField'. But I keep getting
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "thirdField" (class Message), not marked as ignorable (2 known properties: , "type", "producer"])
Ignoring unknown properties using @JsonIgnoreProperties If you are creating a Model class to represent the JSON in Java, then you can annotate the class with @JsonIgnoreProperties (ignoreUnknown = true) to ignore any unknown field.
@JsonIgnore is to ignore fields used at field level. while, @JsonIgnoreProperties is used at class level, used for ignoring a list of fields. Annotation can be applied both to classes and to properties.
The. @JsonIgnoreProperties. annotation is used at the class level to ignore fields during serialization and deserialization. The properties that are declared in this annotation will not be mapped to the JSON content.
@JsonIgnoreProperties. @JsonIgnoreProperties is a class-level annotation that marks a property or a list of properties that Jackson will ignore. Let's look at a quick example ignoring the property id from serialization: @JsonIgnoreProperties({ "id" }) public class BeanWithIgnore { public int id; public String name; }
You've mixed different versions of Jackson.
Notice that you import JsonIgnoreProperties
from org.codehaus.jackson.annotate
(version 1.x)
while you're using ObjectMapper
from com.fasterxml.jackson.databind
(version 2.x).
Try using the last Jackson version (2.4):
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties({"id"})
Here you can find an example where it's implement using version 2.4: http://www.ibm.com/developerworks/java/library/j-hangman-app/index.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With