Using Jackson to deserialize a JSON response into a DTO.
For a given response:
[ {
foo : "bar",
value : "hello world"
},
{
foo : "bar",
value : "hello world"
},
{
foo : "bar",
value : "hello world"
},
{
foo : "bar",
} ]
You can see that all the objects in this array but one of them is inconsistent in the schema (the last one).
After looking at some other related questions on StackOverflow:
deserializing json using jackson with missing fields
Ignore null fields when DEserializing JSON with Gson or Jackson
They still create an object from that irregular JSON object.
Which means I need to then iterate through this list and delete any objects that do not have the attribute "value" by implementing a cleaning method.
What I want to know is can Jackson do this business logic for me?
If this JSON object has all the required fields
Then create a new DTO
Else
Skip to next JSON object in response
My DTO with Jackson annotations:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public final class FooDTO {
private final String foo;
private final String value;
/**
* Constructor
*
* @param foo String
* @param value String
*/
@JsonCreator
public FooDTO(@JsonProperty("foo") final String foo, @JsonProperty("value") final String value) {
this.foo = checkNotNull(foo, "foo required");
this.value = value;
}
@JsonProperty("foo")
public void setFoo(final String foo) {
this.foo = foo;
}
/**
* @return String
*/
public String foo() {
return foo;
}
etc...
With the result from the given JSON response being 3 DTOs being initialised, rather than 4.