java解析json,然后将其转换为xml
1、解析附件的person.json文件,然后生成一个person.xml文件。{"teachers":[{"name":"黄波","course":"网页高级设计"},...
1、解析附件的person.json文件,然后生成一个person.xml文件。
{
"teachers":[
{"name":"黄波","course":"网页高级设计"},
{"name":"贺敏","course":"Java程序设计"},
{"name":"毛丽娟","course":"JavaScript程序设计"}
],
"students":[
{"name":"张三","age":20},
{"name":"李四","age":21},
{"name":"王五","age":19}
]
} 展开
{
"teachers":[
{"name":"黄波","course":"网页高级设计"},
{"name":"贺敏","course":"Java程序设计"},
{"name":"毛丽娟","course":"JavaScript程序设计"}
],
"students":[
{"name":"张三","age":20},
{"name":"李四","age":21},
{"name":"王五","age":19}
]
} 展开
1个回答
展开全部
需要的依赖:
<dependency>
<groupId>de.odysseus.staxon</groupId>
<artifactId>staxon</artifactId>
<version>1.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();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询