Friday, 9 August 2013

Easy way to convert an XML to JSON with some customization

Here I am going  to discuss an easy way to convert an XML to JSON by applying some customization.
There are lot of way by using this an XML can be converted to JSON , among one easiest way is using XSLT.
XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.
XSLT stands for XSL Transformations.Earlier using this an XML document used to convert  to HTML to view the XML in browser with design. Here we will extends the same concept to convert an XML doc to JSON.

Now lets take an example XML doc which we will convert into JSON using XSLT
<Message>

    <books>

        <book price="10">

            <name>Java</name>

            <Author>Krushna</Author>

            <publish>2014</publish>

        </book>

        <book price="40">

            <name>J2EE</name>

            <Author>Krish</Author>

            <publish>2015</publish>

        </book>

        <book price="30">

            <name>Spring</name>

            <Author>Krushna</Author>

            <publish>2015</publish>

        </book>

    </books>

</Message>


We want to convert the above XML to JSON like below with some customization like
We don't want the <Message> part and year of publish in JSON . We wnat to change the some of the attribute name.(We can apply any customization according to requirements) So our JSON should look like.
{
   "books": {
      "book": [
        {
          "p": "10",
          "name": "Java",
          "Author": "Krushna",
          
        },
        {
          "p": "40",
          "name": "J2EE",
          "Author": "Krish",
        },
        {
          "-p": "30",
          "name": "Spring",
          "Author": "Krushna",
        }
      ]
    }
}

So for that we required to write the XSLT  file with the rule and it will be like below.


	
	

	
		 
   	 {
   	  	"Books":[

		
			
			{
			"p":"
			
			",
	   		"name":"
			
			"
	   		,
		"Author":"
			
			"
			
			}
			
			
				
					
		]
				
				
					, 
				
			
		
		}
	

Some explanation about the above xslt.
<xsl:for-each select="Message/books/book">:-Like a for loop to select all book
<xsl:value-of select="@price" />:-to select the attribute price
<xsl:value-of select="name" />:-to select the value of tag.
You can know more about, how to write xslt file for xml from here  with all rule.
Remember the xslt file is responsible for converting the XML to any format. To test it quickly thorugh browser you can save the content of sxlt to a file and including the file in xml  and open the xml in browser and you  browser will convert the xml according to xslt.You can include xslt like below
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="books.xslt"?>
<Message>
    <books>
......

<?xml-stylesheet type="text/xsl" href="books.xslt"?> , here the xslt save in a file called books.xslt.

Now let see how we can write java code to convert it on the fly.

import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

public class XSLTransformation {
	private static Logger log = Logger.getLogger(XSLTransformation.class);
	
	public static void transformation(OutputStream out,  InputStream is, InputStream xsltStream){
		Transformer transformer;
		try {
			TransformerFactory factory = TransformerFactory.newInstance();
			Source xslt = new StreamSource(xsltStream);
			transformer = factory.newTransformer(xslt);
			Source text = new StreamSource(is);
			transformer.transform(text,	new StreamResult(out));
			if(log.isDebugEnabled()){
				log.debug("Conversion completed");
			}
		} catch (TransformerConfigurationException e) {
			log.error("Error "+e);
		} catch (TransformerException e) {
			log.error("Error "+e);
		}
	}

}
In the above class

OutputStream:-to which output json data will be written
InputStream is:-from which it will read the xml data
InputStream xsltStream:-from which it will read the xslt

That is All, Thank you.


No comments:

Post a Comment