Reputation: 53826
Using this code to convert convert Json to a Java object using Jackson annotations :
import com.fasterxml.jackson.databind.ObjectMapper;
import objectmappertest.Request;
import java.io.IOException;
public static void main(String args[]) throws IOException {
final String json = "{\"datePurchased\":\"2022-02-03 21:32:017\"},{\"unknownField\":\"test\"}";
final Request request = mapper.readValue(json, Request.class);
System.out.println("request : "+request);
}
I expect an exception to be thrown as the Request Java object does not contain a field type unknownField
, instead it seems that Jackson parses what it can from the JSON. Is there a configuration option which a causes an exception or a flag to be set if the Json being passed to Jackson does not match the Java object structure ?
Here is the expected structure :
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
import java.util.Date;
@Builder
@ToString
@Getter
@Setter
@Jacksonized
public class Request
{
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:sss")
private final Date datePurchased;
}
Upvotes: 0
Views: 304
Reputation: 8383
FAIL_ON_UNKNOWN_PROPERTIES
Feature that determines whether encountering of unknown properties (ones that do not map to a property, and there is no "any setter" or handler that can handle it) should result in a failure (by throwing a JsonMappingException) or not.
Example of Usage:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
Documentation:
You can also use the annotation @JsonIgnoreProperties
on top of the POJO itself: However I am not quite sure if this will throw an Exception on its own.
@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
Annotation that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization).
Example:
// To throw exception on any unknown properties in JSON input:
@JsonIgnoreProperties
public class YourPoJo{
}
public abstract boolean ignoreUnknown
Property that defines whether it is ok to just ignore any unrecognized properties during deserialization.
If true, all properties that are unrecognized -- that is, there are no setters or creators that accept them -- are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.
Does not have any effect on serialization.
Default: false
Documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html
Upvotes: 1