I've got this JSON : {"success":false}
I want to deserialize this into this POJO :
class Message {
private Map<String, String> dataset = new HashMap<String, String>();
@JsonProperty("success")
public boolean isSuccess() {
return Boolean.valueOf(dataset.get("success"));
}
@JsonProperty("success")
public void setSuccess(boolean success) {
dataset.put("success", String.valueOf(success));
}
}
Is it possible to deserialize this JSON into a class without field success? So far, i've always got the "UnrecognizedPropertyException: Unrecognized field "success""
Thanks for your help!
How to control which fields get serialized/deserialized by Jackson and which fields get ignored. Control your JSON output with Jackson 2 by using a Custom Serializer. 2. Standard Deserialization Let's start by defining 2 entities and see how Jackson will deserialize a JSON representation to these entities without any customization:
The service provider your application is consuming has added a new attribute in the return of the service. Since such an attribute does not exist in your java / DTO object, we have an unrecognized property, making the deserialization process impossible (JSON -> object).
Out of the four fields of the class, just the public booleanValue will be serialized to JSON by default: 3. A Getter Makes a Non-Public Field Serializable and Deserializable
The simplest way to make sure a field is both serializable and deserializable is to make it public. Let's declare a simple class with a public, a package-private and a private
You could implement a method and annotate it with @JsonAnySetter
like this:
@JsonAnySetter
public void handleUnknownProperties(String key, Object value) {
// this will be invoked when property isn't known
}
another possibility would be turn this fail off like this:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
This would let you deserialize your JSON without failing when properties are not found.
public static class Message {
private final Map<String, String> dataset = new HashMap<String, String>();
@Override
public String toString() {
return "Message [dataset=" + dataset + "]";
}
}
@Test
public void testJackson() throws JsonParseException, JsonMappingException, IOException {
String json = "{\"success\":false}";
ObjectMapper om = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
System.out.println(om.readValue(json, Message.class));
}
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