注意:需要引入额外的jar包来支持这个程序“fastjson”。import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import java.io.*;public class Test { public static void main(String[] args) { BaoWenZhuanHuan zhuanHuan = new BaoWenZhuanHuan(); String filePath = "C:\\file\\origin.txt"; //读取文件的路径 String jsonString = zhuanHuan.readTxtFile(filePath); zhuanHuan.Json2Xpath(jsonString); }}class BaoWenZhuanHuan { //获取JSON报文 public String readTxtFile(String filePath) { String jsonString = ""; try { String encoding = "GBK"; File file = new File(filePath); if (file.isFile() && file.exists()) { //判断文件是否存在 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { jsonString += lineTxt; } System.out.println(jsonString); read.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } return jsonString; } public void Json2Xpath(String jsonStr) { System.out.println("json转换成xpath:"); JSONObject json = JSON.parseObject(jsonStr); StringBuffer sb = new StringBuffer(); for (Object key : json.keySet()) { Object value = json.get(key); int flag = 1; sb.append(iteraorJson(value, key, flag)); } System.out.println(sb); outPutTxt(sb); } /** * 迭代判断value是否还包含jSONObject * * @param value * @return */ public String iteraorJson(Object value, Object key1, int flag) { StringBuffer sb = new StringBuffer(""); if ((value.toString().contains(":"))) { JSONObject json = ((JSONObject) value); for (Object key : json.keySet()) { if (flag == 1) { sb.append("/sdoroot").append("/").append(changeKey(key1)); } else { sb.append("/").append(changeKey(key1)); } Object value2 = json.get(key); flag = 2; sb.append(iteraorJson(value2, key, flag)); flag = 1; } } else { if (flag == 1) { sb.append("/sdoroot").append("/").append(changeKey(key1)).append("=").append(value).append("\r\n"); } else { sb.append("/").append(changeKey(key1)).append("=").append(value).append("\r\n"); } } return sb.toString(); } /* 去掉非字母的字符,并且把大写字母转换成小写字母 */ public String changeKey(Object key) { return key.toString().replaceAll("[^a-zA-Z]", "").toLowerCase(); } /*把转换后的结果输出到文件*/ public void outPutTxt(StringBuffer sb) { FileOutputStream fos = null; File file; try { // 指定写入文件的路径 file = new File("C:\\Users\\GNA\\Desktop\\lala.txt"); //转换后的路径 fos = new FileOutputStream(file); /* 先检测文件是否存在,如果不存在则先创建*/ if (!file.exists()) { file.createNewFile(); } /* * 字符串的内容没法直接写到文件,我们需要先使用getBytes转换为bytes。 */ byte[] bytesArray = sb.toString().getBytes(); fos.write(bytesArray); fos.flush(); System.out.println("File Written Successfully"); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ioe) { System.out.println("Error in closing the Stream"); } } }}
java程序实现JSON格式的报文转换成XPATH格式
点赞
收藏