Over a million developers have joined DZone.


DZone's Guide to


· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Yes, it is long time since i posted…

Was just trying to see how a XML can be converted to JSON and to HashMap.

The situation is very imaginary.

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;

    import net.sf.json.JSON;
    import net.sf.json.xml.XMLSerializer;

    import org.apache.commons.io.IOUtils;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.type.TypeReference;

    public class XML2JSONConvertor {
    public static void main(String[] args) throws Exception {

    InputStream is = new FileInputStream(new File(
    String xml = IOUtils.toString(is);

    XMLSerializer xmlSerializer = new XMLSerializer();
    JSON json = xmlSerializer.read(xml);




    public static void printJSON(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();

    try {

    Map<String, Object> jsonInMap = mapper.readValue(jsonString,
    new TypeReference<Map<String, Object>>() {

    List<String> keys = new ArrayList<String>(jsonInMap.keySet());

    for (String key : keys) {
    System.out.println(key + “: ” + jsonInMap.get(key));

    } catch (JsonGenerationException e) {
    } catch (JsonMappingException e) {
    } catch (IOException e) {




The Input XML

<?xml version=”1.0″ encoding=”UTF-8″?>
<name>Jags Inc</name>

The output

7 Feb, 2013 7:20:50 PM net.sf.json.xml.XMLSerializer getType
INFO: Using default type string
“name”: “Jags Inc”,
“employees”: [
"name": "Jagan",
"sex": "Male",
"dob": "24-jul"
"name": "Satya",
"sex": "Male",
"dob": "24-apr"
name: Jags Inc
employees: [{name=Jagan, sex=Male, dob=24-jul}, {name=Satya, sex=Male, dob=24-apr}]


BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}