天天看點

Java實作xml檔案轉json對象

<dependency>

<groupId>org.json</groupId>

<artifactId>json</artifactId>

<version>20160810</version>

</dependency>

更多版本見http://mvnrepository.com/artifact/org.json/json

import org.json.JSONObject;

import org.json.XML;

作者:robinzhang13

連結:https://www.jianshu.com/p/d54e5bc34c9f

來源:簡書

著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

public static String readFile(String path) throws Exception {
    File file=new File(path);
    FileInputStream fis = new FileInputStream(file);
    FileChannel fc = fis.getChannel();
    ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
    //fc向buffer中讀入資料
    fc.read(bb);
    bb.flip();
    String str=new String(bb.array(),"UTF8");
    fc.close();
    fis.close();
    return str;

}      
public static void xmlStrToJsonStr(String xml) throws Exception {

   
    String filename="C:\\Users\\admin\\Desktop\\test2.xml";
    String xmlStr2= readFile(filename);
    org.json.JSONObject jsonObj = XML.toJSONObject(xmlStr2);
    System.out.println(jsonObj);

}