Here's a small example demonstrating how to convert JSON to XML using JAXB data binding. You might want to use this over streaming where you want to operate on objects in an intermediary step. It is possible to perform the reverse operation but that is not demonstrated here.
- Java 7
- Jackson 2.2
- jackson-core-2.2.0.jar
- jackson-databind-2.2.0.jar
- jackson-annotations-2.2.0.jar
- jackson-module-jaxb-annotations-2.2.0.jar
The sample JSON input is an array of simple records:
[{"id":100,"name":"foo"},{"id":200,"name":"bar"}]
The expected XML output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <records> <record id="100" name="foo"/> <record id="200" name="bar"/> </records>
Sample code:
import java.io.*; import java.util.List; import javax.xml.bind.JAXB; import javax.xml.bind.annotation.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; public class Json2Xml { public static void main(String[] args) throws IOException { try (InputStream in = new FileInputStream(args[0]); OutputStream out = new FileOutputStream(args[1])) { Records root = read(in); write(root, out); } } private static Records read(InputStream in) throws IOException { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector( mapper.getTypeFactory()); mapper.setAnnotationIntrospector(introspector); Records root = new Records(); root.records = mapper.readValue(in, new TypeReference<List<Record>>() {}); return root; } private static void write(Records root, OutputStream out) throws IOException { JAXB.marshal(root, out); } @XmlRootElement public static class Records { @XmlElements(@XmlElement(name = "record")) public List<Record> records; } public static class Record { @XmlAttribute public int id; @XmlAttribute public String name; } }
This is only demo code but you could clean it up with getters/setters/etc.
No comments:
Post a Comment
All comments are moderated