com.fitbur.fasterxml.jackson.module.jaxb.ser.DomElementJsonSerializer Maven / Gradle / Ivy
package com.fitbur.fasterxml.jackson.module.jaxb.ser;
import java.io.IOException;
import java.lang.reflect.Type;
import com.fitbur.w3c.dom.*;
import com.fitbur.fasterxml.jackson.core.*;
import com.fitbur.fasterxml.jackson.databind.JsonMappingException;
import com.fitbur.fasterxml.jackson.databind.JsonNode;
import com.fitbur.fasterxml.jackson.databind.SerializerProvider;
import com.fitbur.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fitbur.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Ryan Heaton
*/
public class DomElementJsonSerializer
extends StdSerializer
{
public DomElementJsonSerializer() { super(Element.class); }
@Override
public void serialize(Element value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException
{
jgen.writeStartObject();
jgen.writeStringField("name", value.getTagName());
if (value.getNamespaceURI() != null) {
jgen.writeStringField("namespace", value.getNamespaceURI());
}
NamedNodeMap attributes = value.getAttributes();
if (attributes != null && attributes.getLength() > 0) {
jgen.writeArrayFieldStart("attributes");
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr) attributes.item(i);
jgen.writeStartObject();
jgen.writeStringField("$", attribute.getValue());
jgen.writeStringField("name", attribute.getName());
String ns = attribute.getNamespaceURI();
if (ns != null) {
jgen.writeStringField("namespace", ns);
}
jgen.writeEndObject();
}
jgen.writeEndArray();
}
NodeList children = value.getChildNodes();
if (children != null && children.getLength() > 0) {
jgen.writeArrayFieldStart("children");
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
jgen.writeStartObject();
jgen.writeStringField("$", child.getNodeValue());
jgen.writeEndObject();
break;
case Node.ELEMENT_NODE:
serialize((Element) child, jgen, provider);
break;
}
}
jgen.writeEndArray();
}
jgen.writeEndObject();
}
@Override
public JsonNode getSchema(SerializerProvider provider, Type typeHint)
throws JsonMappingException
{
ObjectNode o = createSchemaNode("object", true);
o.put("name", createSchemaNode("string"));
o.put("namespace", createSchemaNode("string", true));
o.put("attributes", createSchemaNode("array", true));
o.put("children", createSchemaNode("array", true));
return o;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy