Strive for reuse
Answer
nafas seems to give you what you need for this problem. Similar to an alternative approach: removing unwanted objects can be tied to a single use case, therefore it can be ideal to separate the removal from deserialization. You can do this by deserializing your JSON as it is, and then filter out unwanted objects when you need to.
Create an object that represents your JSON
Such an object will allow you to translate JSON into Java and perform operations on data in a more formalized way compared to using JsonNode . You donโt know how Jackson behaves with spaces in property names, it just follows the JSON example.
public class CustomPojo { private final Integer keyToKeep; private final String keyToRemove; @JsonCreator public CustomPojo(@JsonProperty("Lorem Ipsum ") Integer keyToKeep, @JsonProperty("keyToRemove") String keyToRemove) { this.keyToKeep = keyToKeep; this.keyToRemove = keyToRemove; } @JsonProperty("Lorem Ipsum ") public Integer getKeyToKeep() { return keyToKeep; } @JsonProperty("keyToRemove") public String getKeyToRemove() { return keyToRemove; } }
Add a method to remove unwanted objects
Adding a method to delete objects will cancel the deletion from deserialization. Assuming you will deserialize your JSON into an array of your resource.
public class CustomPojoService { public static List<CustomPojo> removeUnwantedKeys(List<CustomPojo> customPojoArray) { return customPojoArray.stream().filter( customPojo -> customPojo.getKeyToRemove() == null ).collect(Collectors.toList()); } }
source share