Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convert Xml to Json format using java

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 7.84k
    Comment on it

    Xml to Json conversion:

    Lets see with the help of example.

    Following jars are required for conversion:

    • apache-commmons
    • json-lib
    • ezmorph

    Suppose we have the xml file with name demo.xml with the following data:

    <!--?xml version="1.0" encoding="UTF-8"?-->
    <group>
       <person id="01">
          <Name>Shawn Michael</Name>
          <Age>36</Age>
          <Gender>Male</Gender>
          <Nationality>Indonesian</Nationality>
       </person>
       <person id="02">
          <Name>Dev Gaba</Name>
          <Age>24</Age>
          <Gender>Male</Gender>
          <Nationality>Indian</Nationality>
       </person>
       <person id="03">
          <Name>Shikha Gulati</Name>
          <Age>22</Age>
          <Gender>Female</Gender>
          <Nationality>Indian</Nationality>
       </person>
    </group>

    This file should be placed in the same path as classpath.
    Java code for conversion is:

    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import org.apache.commons.io.IOUtils;
    import net.sf.json.JSON;
    import net.sf.json.xml.XMLSerializer;
    
    public class ConvertToJson {
          private static URL url = null;
            private static InputStream input = null;   
            public static void main(String args[]) throws IOException {
                try{
                    url = ConvertToJson.class.getClassLoader().getResource("example.xml");
                    input = url.openStream();
                    String xmlData = IOUtils.toString(input);
                    XMLSerializer xmlSerializer = new XMLSerializer();  
                    JSON json = xmlSerializer.read(xmlData);
                    System.out.println("JSON format : " + json);
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
    
                        input.close();
                       }
    
    
                }
            }
    
    Output:
    JSON format : [{"@id":"01","Name":"Shawn Michael","Age":"36","Gender":"Male","Nationality":"Indonesian"},{"@id":"02","Name":"Dev Gaba","Age":"24","Gender":"Male","Nationality":"Indian"},{"@id":"03","Name":"Shikha Gulati","Age":"22","Gender":"Female","Nationality":"Indian"}]

     

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: