Skip to content

Commit

Permalink
Handle duplicate elements as Array when converting XML to JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmara-pc14 committed Apr 8, 2021
1 parent 83459f3 commit 06a33e4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.paymentcomponents.libraries.rest.sdk.wrapper.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class DuplicateToArrayJsonNodeDeserializer extends JsonNodeDeserializer {

@Override
protected void _handleDuplicateField(JsonParser p, DeserializationContext ctxt,
JsonNodeFactory nodeFactory, String fieldName, ObjectNode objectNode,
JsonNode oldValue, JsonNode newValue) throws JsonProcessingException {
ArrayNode node;
if (oldValue instanceof ArrayNode) {
node = (ArrayNode) oldValue;
node.add(newValue);
} else {
node = nodeFactory.arrayNode();
node.add(oldValue);
node.add(newValue);
}
objectNode.set(fieldName, node);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.paymentcomponents.libraries.rest.sdk.wrapper.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import javax.xml.datatype.DatatypeConfigurationException;
Expand All @@ -17,11 +18,16 @@ public static String convertXmlToJson(String xml, String additionalRootElement)
String json = "";
try {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.registerModule(new SimpleModule().addDeserializer(
JsonNode.class,
new DuplicateToArrayJsonNodeDeserializer()
));
JsonNode node = xmlMapper.readTree(xml.getBytes());
json = node.toString();
if (additionalRootElement != null && !additionalRootElement.isEmpty()) {
json = "{ \"" + additionalRootElement + "\": " + json + " } ";
}
json = json.replaceAll("\"\":", "\"Value\":");
} catch (Exception e) {
e.printStackTrace();
}
Expand Down

0 comments on commit 06a33e4

Please sign in to comment.