|
1 |
| -package cloud.eppo.ufc.dto; |
| 1 | +package cloud.eppo.api; |
2 | 2 |
|
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.fasterxml.jackson.databind.node.ObjectNode; |
3 | 6 | import java.util.HashMap;
|
4 | 7 | import java.util.Map;
|
5 | 8 | import java.util.stream.Collectors;
|
@@ -61,4 +64,43 @@ public Attributes getCategoricalAttributes() {
|
61 | 64 | public Attributes getAllAttributes() {
|
62 | 65 | return this;
|
63 | 66 | }
|
| 67 | + |
| 68 | + /** Serializes the attributes to a JSON string, omitting attributes with a null value. */ |
| 69 | + public String serializeNonNullAttributesToJSONString() { |
| 70 | + return serializeAttributesToJSONString(true); |
| 71 | + } |
| 72 | + |
| 73 | + @SuppressWarnings("SameParameterValue") |
| 74 | + private String serializeAttributesToJSONString(boolean omitNulls) { |
| 75 | + ObjectMapper mapper = new ObjectMapper(); |
| 76 | + ObjectNode result = mapper.createObjectNode(); |
| 77 | + |
| 78 | + for (Map.Entry<String, EppoValue> entry : entrySet()) { |
| 79 | + String attributeName = entry.getKey(); |
| 80 | + EppoValue attributeValue = entry.getValue(); |
| 81 | + |
| 82 | + if (attributeValue == null || attributeValue.isNull()) { |
| 83 | + if (!omitNulls) { |
| 84 | + result.putNull(attributeName); |
| 85 | + } |
| 86 | + } else { |
| 87 | + if (attributeValue.isNumeric()) { |
| 88 | + result.put(attributeName, attributeValue.doubleValue()); |
| 89 | + continue; |
| 90 | + } |
| 91 | + if (attributeValue.isBoolean()) { |
| 92 | + result.put(attributeName, attributeValue.booleanValue()); |
| 93 | + continue; |
| 94 | + } |
| 95 | + // fall back put treating any other eppo values as a string |
| 96 | + result.put(attributeName, attributeValue.toString()); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + try { |
| 101 | + return mapper.writeValueAsString(result); |
| 102 | + } catch (JsonProcessingException e) { |
| 103 | + throw new RuntimeException(e); |
| 104 | + } |
| 105 | + } |
64 | 106 | }
|
0 commit comments