Skip to content

Instantly share code, notes, and snippets.

@nbarraille
Last active July 19, 2016 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbarraille/6804fe0d69ddfd3be22399d3b1727c4a to your computer and use it in GitHub Desktop.
Save nbarraille/6804fe0d69ddfd3be22399d3b1727c4a to your computer and use it in GitHub Desktop.
// Deserializing list with invalid object
String json = "[{\"id\":\"123\"}, {}, {\"id\":\"125\"}]";
ObjectMapper mapper = new ObjectMapper();
List<MyObject> objects = mapper.readValue(json, new TypeReference<List<MyObject>>() {});
// This will throw IllegalArgumentException
// How can I make this return [MyObject{id=123}, [MyObject{id=125}] instead?
// Custom Object
@JsonDeserialize(builder = MyObject.Builder.class)
public class MyObject {
@NonNull
private final String id;
private MyObject(@NonNull String id) {
this.id = id;
}
@NonNull
public String getId() {
return id;
}
public static class Builder {
private String id;
@JsonProperty("id")
public Builder setId(@NonNull String id) {
this.id = id;
return this;
}
public MyObject build() {
if (id == null) {
throw new IllegalStateException("id is null");
}
return new MyObject(id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment