Skip to content

Commit 88e1449

Browse files
authored
Merge pull request #1147 from HubSpot/nullvalue-serilization
Add custom serializer for NullValue.
2 parents 3f78a3c + 7c6e5d7 commit 88e1449

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

src/main/java/com/hubspot/jinjava/interpret/NullValue.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,42 @@
11
package com.hubspot.jinjava.interpret;
22

3+
import com.fasterxml.jackson.core.JsonGenerator;
4+
import com.fasterxml.jackson.databind.SerializerProvider;
5+
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
6+
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
7+
import com.hubspot.jinjava.interpret.NullValue.NullValueSerializer;
8+
import java.io.IOException;
9+
310
/**
411
* Marker object of a `null` value. A null value in the map is usually considered
512
* the key does not exist. For example map = {"a": null}, if map.get("a") == null,
613
* we treat it as the there is not key "a" in the map.
714
*/
15+
@JsonSerialize(using = NullValueSerializer.class)
816
public final class NullValue {
917

1018
public static final NullValue INSTANCE = new NullValue();
1119

20+
public static class NullValueSerializer extends StdSerializer<NullValue> {
21+
22+
public NullValueSerializer() {
23+
this(null);
24+
}
25+
26+
protected NullValueSerializer(Class<NullValue> t) {
27+
super(t);
28+
}
29+
30+
@Override
31+
public void serialize(
32+
NullValue value,
33+
JsonGenerator jgen,
34+
SerializerProvider provider
35+
) throws IOException {
36+
jgen.writeNull();
37+
}
38+
}
39+
1240
private NullValue() {}
1341

1442
public static NullValue instance() {
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.hubspot.jinjava.interpret;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import com.fasterxml.jackson.core.JsonProcessingException;
6+
import com.fasterxml.jackson.databind.ObjectMapper;
7+
import com.google.common.collect.ImmutableMap;
8+
import org.junit.Test;
9+
10+
public class NullValueTest {
11+
12+
@Test
13+
public void itSerializesUnderlyingValue() throws JsonProcessingException {
14+
LazyExpression expression = LazyExpression.of(
15+
() -> ImmutableMap.of("test", "hello", "test2", NullValue.instance()),
16+
"{}"
17+
);
18+
Object evaluated = expression.get();
19+
assertThat(evaluated).isNotNull();
20+
assertThat(new ObjectMapper().writeValueAsString(expression))
21+
.isEqualTo("{\"test\":\"hello\",\"test2\":null}");
22+
}
23+
}

0 commit comments

Comments
 (0)