需求背景:
- 项目提供接口给安卓的app,由于数据量较大,初步方案通过sql lite来在app安装的时候初始化。源数据为oracle格式,统一处理为json。
package xml2json;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IoUtils;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
public class Test {
public static void ConvertXMLtoJSON() throws FileNotFoundException {
String d ="C:\\Users\\Administrator\\Desktop\\部门信息.xml";
File file=new File(d);
//读取文件流
FileInputStream in = new FileInputStream(file);
String xml;
try {
xml = IoUtils.toString(in);
System.out.println(xml);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xml);
System.out.println(json.toString(1));
//处理返回为空数组的数据
String tojson=json.toString().replace("[]","null");
File fileRs=new File("C:\\Users\\Administrator\\Desktop\\部门信息表.txt");
if (!fileRs.exists()) {// 如果文件不存在,则创建该文件
fileRs.createNewFile();
}
FileWriter fw=new FileWriter(fileRs);
fw.write(tojson.toString());
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException {
ConvertXMLtoJSON();
}
}