Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 

 1 Answer(s)

  • Xml to Json conversion:

    Lets see with the help of example.

    Following jars are required:

    • apache-commmons
    • json-lib
    • ezmorph

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

    <!--?xml version="1.0" encoding="UTF-8"?-->
    <group>
       <person id="p01">
          <Name>Mathew Hayden</Name>
          <Age>35</Age>
          <Gender>Male</Gender>
          <Nationality>Aussie</Nationality>
       </person>
       <person id="p02">
          <Name>Rohit Sharma</Name>
          <Age>27</Age>
          <Gender>Male</Gender>
          <Nationality>Indian</Nationality>
       </person>
       <person id="p03">
          <Name>Sonali Sharma</Name>
          <Age>22</Age>
          <Gender>Female</Gender>
          <Nationality>Indian</Nationality>
       </person>
    </group>
    

    This file should be placed under src folder for this code.
    We write a java code to convert this to Json format as:

    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 data : " + json);
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
    
                        input.close();
                       }
    
    
                }
            }
    

    Output:

    JSON data : [{"@id":"p01","Name":"Mathew Hayden","Age":"35","Gender":"Male","Nationality":"Aussie"},{"@id":"p02","Name":"Rohit Sharma","Age":"27","Gender":"Male","Nationality":"Indian"},{"@id":"p03","Name":"Sonali Sharma","Age":"22","Gender":"Female","Nationality":"Indian"}]
    
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: