user3349808
user3349808

Reputation: 99

How to convert XML file to json

I want to convert my xml file to json...but below code shows null pointer exception..i don't know what went wrong.

public class Xmljson {  
    private URL url = null;
    private InputStream inputStream = null;  

    public void getXMLfromJson() {
        try{
            url = Xmljson.class.getClassLoader().getResource("datafile.xml");
            inputStream = url.openStream();
            String xml = IOUtils.toString(inputStream);
            JSON objJson = new XMLSerializer().read(xml);
            System.out.println("JSON data : " + objJson);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
           try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {}
        }
    }   

    public static void main(String[] args) {
        new Xmljson().getXMLfromJson();
    }
}

shows exception here

         url = Xmlto.class.getClassLoader().getResource("data");
            inputStream = url.openStream();

NPE IS

java.lang.NullPointerException
at pkg.news.Xmlto.getXMLfromJson(Xmlto.java:19)
at pkg.news.Xmlto.main(Xmlto.java:35)

referred from

http://tutorial4java.blogspot.in/2013/04/xml-to-json-conversion.html

Upvotes: 1

Views: 15830

Answers (2)

chopss
chopss

Reputation: 811

Check this out...this works perfect....

  public class Xml2json {

    static String line="",str="";
    public static void main(String[] args) throws JSONException, IOException {
        String link = "data.xml";
        BufferedReader br = new BufferedReader(new FileReader(link));
        while ((line = br.readLine()) != null) 
        {   
            str+=line;  
        }
        JSONObject jsondata = XML.toJSONObject(str);
        System.out.println(jsondata);
    }
}

Upvotes: 5

kmario23
kmario23

Reputation: 61305

It should work

url = XMLjson.class.getClassLoader().getResource("datafile.xml");

Have you added these statements as well,

import java.io.InputStream;  
import java.net.URL;  
import net.sf.json.JSON;  
import net.sf.json.xml.XMLSerializer;  
import org.apache.commons.io.IOUtils;  

Take a look at here as well http://tutorial4java.blogspot.in/2013/04/xml-to-json-conversion.html

Upvotes: 0

Related Questions