diff --git a/pom.xml b/pom.xml index 634beb2..20378e0 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ black.door hate - v1r0t2 + v1r0t3 diff --git a/src/main/java/black/door/hate/HalRepresentation.java b/src/main/java/black/door/hate/HalRepresentation.java index 9cff338..fb74bfd 100644 --- a/src/main/java/black/door/hate/HalRepresentation.java +++ b/src/main/java/black/door/hate/HalRepresentation.java @@ -131,6 +131,7 @@ public static class HalRepresentationBuilder{ private Map embedded; private Map> multiEmbedded; private Map properties; + private boolean ignoreNullProperties = false; public HalRepresentationBuilder() { links = new HashMap<>(); @@ -140,8 +141,21 @@ public HalRepresentationBuilder() { properties = new HashMap<>(); } + /** + * Causes any properties with null values added to this builder after this call to be ignored. + * Properties with null values added before this call will still be included. + * Null properties are included by default. + * @param active + * @return this builder + */ + public HalRepresentationBuilder ignoreNullProperties(boolean active){ + this.ignoreNullProperties = active; + return this; + } + public HalRepresentationBuilder addProperty(String name, Object prop){ - properties.put(name, prop); + if(!ignoreNullProperties || prop != null) + properties.put(name, prop); return this; } diff --git a/src/test/java/black/door/hate/HalRepresentationTest.java b/src/test/java/black/door/hate/HalRepresentationTest.java index 0c9d16b..0461423 100644 --- a/src/test/java/black/door/hate/HalRepresentationTest.java +++ b/src/test/java/black/door/hate/HalRepresentationTest.java @@ -96,6 +96,25 @@ public void testNulls() throws Exception{ System.out.println(orderz.serialize()); } + @Test + public void testIgnoreNullProp(){ + HalRepresentation rep = HalRepresentation.builder() + .ignoreNullProperties(true) + .addProperty("thing", "value") + .addProperty("nullthing", null) + .build(); + assertFalse(rep.getProperties().containsKey("nullthing")); + assertTrue(rep.getProperties().containsKey("thing")); + + HalRepresentation rep2 = HalRepresentation.builder() + .addProperty("thing", "value") + .addProperty("nullthing", null) + .build(); + assertTrue(rep2.getProperties().containsKey("nullthing")); + assertTrue(rep2.getProperties().containsKey("thing")); + } + + @Test public void testSerialize() throws Exception { val basket1 = new Basket(98712);