Java 进阶 & 文件操作 Xml转化成Json的三种方式

Xml转化成json的三种方式:

方法一: 使用json-lib框架, 需要的依赖包比较多
Java 进阶 & 文件操作 Xml转化成Json的三种方式_第1张图片
image.png

1 、这里通过Class的getResourceAsStream方法获得指定文件的输入流,这里指定参数没有带/,表示Test类与xml文件在同一级目录下,如果有/那么是从根目录进行获取的,
2 、之后利用IOUtils的toString方法将该输入流转化为xml格式的字符串输出,调用XMLSerializer的read方法接受xml格式的字符串,将其转化为JSON对象
3、 这里实际上输出json对象和调用json对象的toString方法输出的形式在控制台展示的是一样的

public class Test {

      public static void ConvertXMLtoJSON()  {

            InputStream is = Test.class.getResourceAsStream("student.xml");

            String xml;

            try {

                xml = IOUtils.toString(is);

                System.out.println(xml);

                XMLSerializer xmlSerializer = new XMLSerializer();

                JSON json = xmlSerializer.read(xml);

                System.out.println(json);

                System.out.println(json.toString(0));

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

      public static void main(String[] args) {

        Test.ConvertXMLtoJSON();

    }

}
方法二:使用 org.json、 commons-io框架

需要导入包:


    org.json
    json
    20160810


    commons-io
    commons-io
    2.5

public class JsonUtils {
public static String XmlToJson2(String  filepath) throws IOException {
    FileInputStream in = new FileInputStream(new File(filepath)) ;
    String xml = IOUtils.toString(in,"utf-8");
    JSONObject object =  XML.toJSONObject(xml);
    return  object.toString();
}

public static void main(String[] args) throws JSONException, IOException {
String path =System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"pushClaim.xml";
String jsonpath  =System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"test2.json";
System.out.println(path);
String json =  XmlToJson2(path);
FileUtils.writeStringToFile(new File(jsonpath),json,"utf-8");
    }
}

输出如:

{
  "claim": {
    "accHistories": {
      "claimNo": "lncl20170626050101",
      "dutyType": "02",
      "coverageName": "第三者责任险",
      "accidentNo": "lnacc2017062605",
      "lossVehicleType": "01",
      "plateNo": "京WQ3008",
      "caseStatus": "处理中",
      "damageSummary": "操作失误,碰擦",
      "totalEstimateAmount": 1.0E8,
      "commercialPaidAmount": 2000000,
      "damageDate": "2017-05-04T03:00:00.560+08:00",
      "compulsoryPolicyNo": "SHEN201311120001",
      "compulsoryPaidAmount": 3000000,
      "coverageCode": 10
    },
    "surveyInfo": {
      "surveyType": "01",
      "accidentType": "01"
    },
    "xsi:type": "vehicleClaimRequestTmp",
    "claimInfo": {
      "claimNo": "lncl20170626050101",
      "tenementId": 0,
      "entrustLimitAmount": 100,
      "commercialPolicyNo": "Policy20161207002",
      "accidentNo": "lnacc2017062605",
      "claimSource": 1,
      "validFlag": 1,
      "transferNo": 0,
      "estimateCompanyId": 2366,
      "entrustFlag": 0,
      "quickCompensateFlag": 1,
      "bigCaseFlag": 0,
      "taskType": "01",
      "operableCompanyId": 2366,
      "claimCompanyId": 2366,
      "compulsoryPolicyNo": "Policy20161207001",
      "reportNo": "BA0001"
    },.....
方法三: 使用 jdom、 fastjson 框架
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class XmlToJson1 {
    public static void main(String[] args) throws IOException {
        String path =System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"pushClaim.xml";
        String jsonpath =System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"test1.json";
        String json = XmlToJson(new File(path));
        System.out.println(json);
        FileUtils.writeStringToFile(new File(jsonpath),json,"utf-8");
    }
    public static String XmlToJson(File file){
        JSONObject object = new JSONObject();
        SAXBuilder builder = null;
        try {
            builder = new SAXBuilder();
            Document document = builder.build(file);
            Element element =document.getRootElement();
            object.put(element.getName(),IterateElement(element));
            return object.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }
    }

    private static Map IterateElement(Element element){
        List node = element.getChildren();
        List list = null;
        Map map = new HashMap();
        for(int i=0;i

输出如:

{
  "claim": {
    "accHistories": [
      {
        "claimNo": [
          "lncl20170626050101"
        ],
        "dutyType": [
          "02"
        ],
        "coverageName": [
          "第三者责任险"
        ],
        "accidentNo": [
          "lnacc2017062605"
        ],
        "lossVehicleType": [
          "01"
        ],
        "plateNo": [
          "京WQ3008"
        ],
        "caseStatus": [
          "处理中"
        ],
        "damageSummary": [
          "操作失误,碰擦"
        ],
        "totalEstimateAmount": [
          "100000000.00"
        ],
        "commercialPaidAmount": [
          "2000000.00"
        ],
        "damageDate": [
          "2017-05-04T03:00:00.560+08:00"
        ],
        "compulsoryPolicyNo": [
          "SHEN201311120001"
        ],
        "compulsoryPaidAmount": [
          "3000000.00"
        ],
        "coverageCode": [
          "10"
        ]
      }
    ],

你可能感兴趣的:(Java 进阶 & 文件操作 Xml转化成Json的三种方式)