import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.mapped.MappedNamespaceConvention; import org.codehaus.jettison.mapped.MappedXMLStreamWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.StringWriter; public class JsonToXmlConverter { public static String convertJsonToXml(String json) throws JSONException, XMLStreamException { JSONObject jsonObject = new JSONObject(json); StringWriter writer = new StringWriter(); XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(new MappedNamespaceConvention()); xmlStreamWriter.setWriter(writer); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("root"); xmlStreamWriter.writeStartElement("data"); xmlStreamWriter.writeCharacters(jsonObject.toString()); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.close(); return writer.toString(); } public static void main(String[] args) { String json = "{\"name\":\"John\", \"age\":30}"; try { String xml = convertJsonToXml(json); System.out.println(xml); e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文