我是JAVA编程的新手,并尝试使用下面的snipet将XML转换为JAVA。
输入文件:
<?xml version="1.0" encoding="UTF-8"?>
-<ns0:MT_ECCJDBC xmlns:ns0="urn:xml:json">
-<REQUEST>
<ID>46565665</ID>
</REQUEST>
</ns0:MT_ECCJDBC>
输出:
{
"@xmlns:ns0": "urn:xml:json",
"REQUEST": ["46565665"]
}
JSON中的预期输出是
{
"REQUEST":
{
" ID " : ["46565665"]
}
}
以下是我的java代码:
public class ConversionXMLtoJSON {
public static void main(String[] args) throws Exception {
{
InputStream is = ConversionXMLtoJSON.class.getResourceAsStream("instance.xml");
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
}
请建议我添加代码
此致
答案 0 :(得分:0)
您可以将XML映射到Java对象,然后使用JSON生成器生成JSON。我喜欢使用jackson-mapper-asl,jackson-core-asl和jackson-dataformat-xml。
将XML绑定到Java:
public class XmlRequest {
@JacksonXmlElementWrapper(localName="REQUEST")
private REQUEST request;
public static class REQUEST {
@JacksonXmlProperty(localName="ID")
protected int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
}
public REQUEST getRequest() {
return request;
}
public void setRequest(REQUEST request) {
this.request = request;
}
}
生成JSON:
XmlMapper mapper = new XmlMapper();
XmlRequest request = (XmlRequest) mapper.readValue(App.class.getResourceAsStream("/NewFile.xml"), XmlRequest.class);
StringWriter sw = new StringWriter();
JsonGenerator jsongen = new JsonFactory().createJsonGenerator(System.out);
jsongen.writeStartObject();
jsongen.writeFieldName("REQUEST");
jsongen.writeStartObject();
jsongen.writeFieldName("ID");
jsongen.writeStartArray();
jsongen.writeNumber(request.getRequest().getID());
jsongen.writeEndArray();
jsongen.writeEndObject();
jsongen.writeEndObject();
jsongen.close();