本文目录一览:
java解析json,然后将其转换为xml
需要的依赖:
dependency
groupIdde.odysseus.staxon/groupId
artifactIdstaxon/artifactId
version1.2/version
/dependency
代码:
public static void main(String[] args) throws Exception {
// 输入json文件
String encoding = "UTF-8";
File jsonFile = new File("C:/Users/Administrator/Desktop/person.json");
Long jsonFilelength = jsonFile.length();
byte[] JsonBytes = new byte[jsonFilelength.intValue()];
FileInputStream in = new FileInputStream(jsonFile);
in.read(JsonBytes);
in.close();
String json = new String(JsonBytes, encoding);
// json -- xml
StringReader input = new StringReader(json);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false)
.repairingNamespaces(false).build();
XMLEventReader reader = new JsonXMLInputFactory(config)
.createXMLEventReader(input);
XMLEventWriter writer = XMLOutputFactory.newInstance()
.createXMLEventWriter(output);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
reader.close();
writer.close();
output.close();
input.close();
// 输出成xml文件
File xmlFile = new File("C:/Users/Administrator/Desktop/person.xml");
PrintWriter outFile = new PrintWriter(xmlFile);
outFile.write(output.toString());
outFile.flush();
outFile.close();
}
如何将json文件转为xml格式的文件
json的话,目前比较流行的转换工具是fastjson,使用方便,速度又很快。。可以在JavaBean和String型之间直接转换
xml的话,可以采用XStream来转换。。。
也就是说,你可以先把json的文件内容转换成JavaBean(fastjson),然后再把JavaBean转换成xml(XStream)
json如何转换成xml
网上都有XML和json互相转换的工具,在线就可以转换。注意XML必须有单一的根节点。
?xml version="1.0" encoding="UTF-8" ?
root
node
id1/id
text系统维护/text
children
iduser/id
text人员维护/text
/children
children
idrole/id
text角色维护/text
iconClsicon-reload/iconCls
/children
/node
node
text开发维护/text
children
text元数据/text
stateclosed/state
children
text编辑样式/text
/children
children
iddataview/id
text数据视图/text
/children
/children
children
text权限资源/text
/children
/node
/root