如何在java中将xml转换成.json文件

时间:2023-02-08 21:48:10
  public class ConvertXMLtoJSON {

    public static void main(String[] args) throws Exception {
        InputStream in =             ConvertXMLtoJSON.class.getResourceAsStream("D:\\sample.xml");
        String xml = IOUtils.toString(in);
        XMLSerializer xmlSerializer = new XMLSerializer(); 
        JSON json = xmlSerializer.read(xml);  
        System.out.println(json.toString(2));
    }
      }

but i am getting error

但是我得到了错误

      Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1020)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:358)
at com.apache.poi.ConvertXMLtoJSON.main(ConvertXMLtoJSON.java:13

can u please help me to resolve it This is my xml format ac3 AC3 Phone ACME phone 200.0 1.0 true

你能帮我解决一下吗这是我的xml格式ac3 ac3手机ACME Phone 200.0 1.0 true

i have generated this xml from my excel file and i have convert this xml file to json file

我已经从excel文件生成了这个xml,并将这个xml文件转换为json文件

4 个解决方案

#1


4  

You are trying to read physical File as a classpath Resource, which is wrong

您试图将物理文件作为类路径资源读取,这是错误的

InputStream in = ConvertXMLtoJSON.class.getResourceAsStream("D:\\sample.xml");

Change it to

将其更改为

InputStream in =  new FileInputStream(new File("D:\\sample.xml"));

#2


3  

String xml = IOUtils.toString(in);

Here InputStream in is null so it raise NullPointerException.

这里的InputStream是null,所以它会抛出NullPointerException。

Class#getResourceAsStream(String name) it use to load resource from classpath and normally use in web-based project, and an absolute resource name is constructed from the given resource name using this algorithm:

类# getresour凯撒流(String name)用于从类路径加载资源,通常用于基于web的项目中,使用这种算法从给定的资源名构造一个绝对的资源名:

  1. If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  2. 如果名称以'/' ('\u002f')开头,则资源的绝对名称是名称后面的'/'部分。
  3. Otherwise, the absolute name is of the following form: modified_package_name/name
  4. 否则,绝对名称为以下形式:modified_package_name/name

As Documentation

作为文档

As your file exists in local hard-drive(D:\\sample.xml) better use FileInputStream to load the resouce.

由于您的文件存在于本地硬盘(D:\ sample.xml),最好使用FileInputStream来加载resouce。

InputStream in =  new FileInputStream("D:\\sample.xml");

Find a good related question -

找到一个好的相关问题-

#3


2  

This is the code which is used to convert xml to json

这是用于将xml转换为json的代码

 import org.json.JSONObject;
 import org.json.JSONException;
 import org.json.XML;
 import java.io.*;


 public class ConvertXMLtoJSON2{  
      public static void main(String[] args) throws Exception {  
        String fileName = "D:\\temp.json";
        try {           
            File file = new File ("D:\\output333.xml");  
            InputStream inputStream = new FileInputStream(file);  
            StringBuilder builder =  new StringBuilder();  
            int ptr = 0;  
            while ((ptr = inputStream.read()) != -1 ) {  
                builder.append((char) ptr); 
              //  System.out.println(ptr);
            }  

            String xml  = builder.toString();  
            JSONObject jsonObj = XML.toJSONObject(xml);   
            // System.out.println(jsonObj.toString()); 
            // System.out.println(jsonObj.toString().split(",").length);
            // Assume default encoding.
            FileWriter fileWriter =
                new FileWriter(fileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

            // Always close files.

            for(int i= 0 ;i < jsonObj.toString().split(",").length; i ++) {
               System.out.println(jsonObj.toString().split(",")[i]);
               bufferedWriter.write(jsonObj.toString().split(",")[i]);
               bufferedWriter.write("\n");
            }

            bufferedWriter.close();
        }


            /* 
            String xmlString  = "<?xml version=\"1.0\"?><ASF_Service_ResponseVO id=\"1\"><service type=\"String\">OnboardingV2</service><operation type=\"String\">start_onboarding_session</operation><requested_version type=\"String\">1.0</requested_version><actual_version type=\"String\">1.0</actual_version><server_info type=\"String\">onboardingv2serv:start_onboarding_session&CalThreadId=85&TopLevelTxnStartTime=13b40fe91c4&Host=L-BLR-00438534&pid=3564</server_info><result type=\"Onboarding::StartOnboardingSessionResponse\" id=\"2\"><onboarding_id type=\"String\">137</onboarding_id><success type=\"bool\">true</success></result></ASF_Service_ResponseVO>"; 

            JSONObject jsonObj = XML.toJSONObject(xmlString);  
            System.out.println(jsonObj.toString());  
            */
          catch(IOException ex) {
                System.out.println(
                    "Error writing to file '"
                    + fileName + "'");
                // Or we could just do this:
                // ex.printStackTrace();
            } catch(Exception e) {  
                e.printStackTrace();  
            }
    }  
}

#4


0  

Try the following code:

试试下面的代码:

import org.json.JSONObject;
import org.json.XML;
import java.io.*;

public class ConverterXMLToJSON {
    public static int PRETTY_FACTOR=4;
    public static void main(String[] args) throws Exception {
        String jsonFileName = "src\\main\\resources\\Light.json";
        try {
            File xmlFile = new File("src\\main\\resources\\Light.xml");
            InputStream inputStream = new FileInputStream(xmlFile);
            StringBuilder builder = new StringBuilder();
            int ptr;
            while ((ptr = inputStream.read()) != -1) {
                builder.append((char) ptr);
            }

            String xml = builder.toString();
            JSONObject jsonObj = XML.toJSONObject(xml);
            System.out.print(jsonObj);
            FileWriter fileWriter =
                    new FileWriter(jsonFileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                    new BufferedWriter(fileWriter);
            bufferedWriter.write(jsonObj.toString(PRETTY_FACTOR));
            bufferedWriter.close();
        } catch (IOException ex) {
            System.out.println(
                    "Error writing to file '"
                            + jsonFileName + "'");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

#1


4  

You are trying to read physical File as a classpath Resource, which is wrong

您试图将物理文件作为类路径资源读取,这是错误的

InputStream in = ConvertXMLtoJSON.class.getResourceAsStream("D:\\sample.xml");

Change it to

将其更改为

InputStream in =  new FileInputStream(new File("D:\\sample.xml"));

#2


3  

String xml = IOUtils.toString(in);

Here InputStream in is null so it raise NullPointerException.

这里的InputStream是null,所以它会抛出NullPointerException。

Class#getResourceAsStream(String name) it use to load resource from classpath and normally use in web-based project, and an absolute resource name is constructed from the given resource name using this algorithm:

类# getresour凯撒流(String name)用于从类路径加载资源,通常用于基于web的项目中,使用这种算法从给定的资源名构造一个绝对的资源名:

  1. If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  2. 如果名称以'/' ('\u002f')开头,则资源的绝对名称是名称后面的'/'部分。
  3. Otherwise, the absolute name is of the following form: modified_package_name/name
  4. 否则,绝对名称为以下形式:modified_package_name/name

As Documentation

作为文档

As your file exists in local hard-drive(D:\\sample.xml) better use FileInputStream to load the resouce.

由于您的文件存在于本地硬盘(D:\ sample.xml),最好使用FileInputStream来加载resouce。

InputStream in =  new FileInputStream("D:\\sample.xml");

Find a good related question -

找到一个好的相关问题-

#3


2  

This is the code which is used to convert xml to json

这是用于将xml转换为json的代码

 import org.json.JSONObject;
 import org.json.JSONException;
 import org.json.XML;
 import java.io.*;


 public class ConvertXMLtoJSON2{  
      public static void main(String[] args) throws Exception {  
        String fileName = "D:\\temp.json";
        try {           
            File file = new File ("D:\\output333.xml");  
            InputStream inputStream = new FileInputStream(file);  
            StringBuilder builder =  new StringBuilder();  
            int ptr = 0;  
            while ((ptr = inputStream.read()) != -1 ) {  
                builder.append((char) ptr); 
              //  System.out.println(ptr);
            }  

            String xml  = builder.toString();  
            JSONObject jsonObj = XML.toJSONObject(xml);   
            // System.out.println(jsonObj.toString()); 
            // System.out.println(jsonObj.toString().split(",").length);
            // Assume default encoding.
            FileWriter fileWriter =
                new FileWriter(fileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

            // Always close files.

            for(int i= 0 ;i < jsonObj.toString().split(",").length; i ++) {
               System.out.println(jsonObj.toString().split(",")[i]);
               bufferedWriter.write(jsonObj.toString().split(",")[i]);
               bufferedWriter.write("\n");
            }

            bufferedWriter.close();
        }


            /* 
            String xmlString  = "<?xml version=\"1.0\"?><ASF_Service_ResponseVO id=\"1\"><service type=\"String\">OnboardingV2</service><operation type=\"String\">start_onboarding_session</operation><requested_version type=\"String\">1.0</requested_version><actual_version type=\"String\">1.0</actual_version><server_info type=\"String\">onboardingv2serv:start_onboarding_session&CalThreadId=85&TopLevelTxnStartTime=13b40fe91c4&Host=L-BLR-00438534&pid=3564</server_info><result type=\"Onboarding::StartOnboardingSessionResponse\" id=\"2\"><onboarding_id type=\"String\">137</onboarding_id><success type=\"bool\">true</success></result></ASF_Service_ResponseVO>"; 

            JSONObject jsonObj = XML.toJSONObject(xmlString);  
            System.out.println(jsonObj.toString());  
            */
          catch(IOException ex) {
                System.out.println(
                    "Error writing to file '"
                    + fileName + "'");
                // Or we could just do this:
                // ex.printStackTrace();
            } catch(Exception e) {  
                e.printStackTrace();  
            }
    }  
}

#4


0  

Try the following code:

试试下面的代码:

import org.json.JSONObject;
import org.json.XML;
import java.io.*;

public class ConverterXMLToJSON {
    public static int PRETTY_FACTOR=4;
    public static void main(String[] args) throws Exception {
        String jsonFileName = "src\\main\\resources\\Light.json";
        try {
            File xmlFile = new File("src\\main\\resources\\Light.xml");
            InputStream inputStream = new FileInputStream(xmlFile);
            StringBuilder builder = new StringBuilder();
            int ptr;
            while ((ptr = inputStream.read()) != -1) {
                builder.append((char) ptr);
            }

            String xml = builder.toString();
            JSONObject jsonObj = XML.toJSONObject(xml);
            System.out.print(jsonObj);
            FileWriter fileWriter =
                    new FileWriter(jsonFileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                    new BufferedWriter(fileWriter);
            bufferedWriter.write(jsonObj.toString(PRETTY_FACTOR));
            bufferedWriter.close();
        } catch (IOException ex) {
            System.out.println(
                    "Error writing to file '"
                            + jsonFileName + "'");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}