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

时间:2013-08-21 05:42:26

标签: java xml json

  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));
    }
      }

但我收到错误

      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
你能帮我解决一下吗? 这是我的xml格式                               AC3         AC3手机         ACME         电话         200.0         1.0         真正                                                                                                                                                                                                            

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

5 个答案:

答案 0 :(得分:5)

您正在尝试将实体File读作类路径Resource,这是错误

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

将其更改为

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

答案 1 :(得分:3)

String xml = IOUtils.toString(in);

此处InputStream in为null,因此它会引发NullPointerException

Class#getResourceAsStream(String name)用于从类路径加载资源并通常在基于Web的项目中使用,并使用此算法从给定的资源名称构造绝对资源名称:

  1. 如果名称以'/'('\ u002f')开头,则绝对名称为 资源是'/'。
  2. 后面的名称部分
  3. 否则,绝对名称的格式如下: modified_pa​​ckage_name /名称
  4. 作为Documentation

    由于您的文件存在于本地硬盘驱动器(D:\\sample.xml)中,因此最好使用FileInputStream加载资源。

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

    找一个好的相关问题 -

答案 2 :(得分:2)

这是用于将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();  
            }
    }  
}

答案 3 :(得分:0)

请尝试以下代码:

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();
        }
    }
}

答案 4 :(得分:0)

Underscore-java库可以将xml转换为json。我是该项目的维护者。 Live example

import com.github.underscore.lodash.U;

public class JsonConversion {
    public static void main(String args[]) {
        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"
        + "&amp;CalThreadId=85&amp;TopLevelTxnStartTime=13b40fe91c4&amp;Host=L-BLR-00438534&amp;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>"; 

        String json = U.xmlToJson(xmlString);  
        System.out.println(json);  
    }
}