Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Friday, 19 February 2016

How to get all node names from XML in java

This code logic will help to get all the node names including child nodes from the XML file.

Parsing a below sample XML file:

<USER>
<NAME>Gopal Aggarwal</NAME>
<AGE>26</AGE>

<ADDRESS>
        <CITY> Bangalore</CITY>
        <STATE>Karnataka</STATE>
</ADDRESS>
</USER>

I am create a Set of unique node and print the output in the end.

package com.info.gopal.xml.parsing;

import java.io.File;
import java.io.IOException;

import java.util.LinkedHashSet;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;


public class ReadAndParse {


    public static void main(String[] args) throws ParserConfigurationException,
                                                  SAXException, IOException {
        File inputFile = new File("File Location");
        DocumentBuilderFactory dbfact = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbfact.newDocumentBuilder();
        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();
        NodeList list = doc.getDocumentElement().getChildNodes();
        //Set with node names
        Set<String> nodeSet = new LinkedHashSet<String>();
        nodeSet = getAllNodeName(list,nodeSet); 
        //Printing node name
        for(String node : nodeSet){
            System.out.println(node);
        }
    }

    private static Set<String> getAllNodeName(NodeList list,Set<String> nodeSet) {
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getNodeType() == node.ELEMENT_NODE && node.getNodeType() != node.COMMENT_NODE) {
                nodeSet.add(node.getNodeName());
                if(node.getChildNodes().getLength() > 1){
                    nodeSet = getAllNodeName(node.getChildNodes(),nodeSet);
                }
            }
        }
        return nodeSet;
    }
}


Output :

NAME
AGE
ADDRESS
CITY
STATE

*Comments and feedback are most welcomed, Thanks.

Sunday, 31 May 2015

Create and Parse JSON using jackson in java

Required JSON String with Array:

{"NAME":"USER","AGE":25,"COUNTRY":"INDIA",
  "ADDRESS": [{"STREET":"xys","CITY":"Bangalore","POSTAL CODE":54321}]
}


CreateJson class having logic for creating and parsing JSON

import java.util.ArrayList;
import java.util.List;

public class CreateJson {

    public static void main(String[] args) {

        UserBean userData = new UserBean();
        userData.setName("USER");
        userData.setAge(25);
        userData.setCountry("INDIA");

        AddressBean address = new AddressBean();
        address.setCity("Bangalore");
        address.setPostalCode(54321);
        address.setStreet("xys");
        List<AddressBean> addressList = new ArrayList<AddressBean>();
        addressList.add(address);
       
        userData.setAddressList(addressList);
        String jsonString = JsonUtil.getJSONString(userData);
        System.out.println(jsonString);
       
        //Method Call to Parse JsonString

        parseMyJsonString(jsonString);

    }

    private static void parseMyJsonString(String jsonString) {
        UserBean userBean = JsonUtil.fromJsonToObject(jsonString);
        System.out.println(userBean.getAge());
        List<AddressBean> addressList = userBean.getAddressList();

        for (AddressBean list : addressList) {
            System.out.println("City " + list.getCity());
            System.out.println("Postal Code " + list.getPostalCode());
        }
    }
}

1. Create AddressBean.java


import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class AddressBean {
   
    @JsonProperty("STREET")
    private String street = null;
    @JsonProperty("CITY")
    private String city = null;
    @JsonProperty("POSTAL CODE")
    private int postalCode;
   
    public AddressBean(){
       
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getStreet() {
        return street;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }

    public void setPostalCode(int postalCode) {
        this.postalCode = postalCode;
    }

    public int getPostalCode() {
        return postalCode;
    }
}

2. Create a UserBean.java


import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class UserBean {
  
   @JsonProperty("NAME")
   private String name = null;
    @JsonProperty("AGE")
   private int age = 0;
    @JsonProperty("COUNTRY")
   private String country = null;
   //List of AddressBean
   @JsonProperty("ADDRESS")
   private List<AddressBean> addressList = null;
  
   public UserBean(){
      
   }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return country;
    }

    public void setAddressList(List<AddressBean> addressList) {
        this.addressList = addressList;
    }

    public List<AddressBean> getAddressList() {
        return addressList;
    }
}

3. Create a Util Class having logic for parsing and creating JSON of UserBean object

import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public final class JsonUtil {

    /**
     * Creates a JSON String
     * @param bean
     * @return String
     */

    public static String getJSONString(UserBean bean) {
        String jsonString = null;
        try {
            jsonString = createObjectMapper().writeValueAsString(bean);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * Parse Json string to UserBean Object
     * @param json
     * @return UserBean
     */

    public static UserBean fromJsonToObject(String json) {
        UserBean responseObj = null;
        try {
            responseObj = createObjectMapper().readValue(json, UserBean.class);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        return responseObj;
    }

    /**
     * @return ObjectMapper
     */

    private static ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
                         true);
        mapper.configure(DeserializationConfig.Feature.USE_JAVA_ARRAY_FOR_JSON_ARRAY,
                         true);
        mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
                         true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,
                         true);

        return mapper;
    }
}

*Using jackson-all-1.9.0.jar

*Comments and feedback are most welcomed, Thanks.

Creating and parsing JSON using Json-simple



1. Simple JSON string creation.

Requirement: {"NAME":"USER","AGE":25,"COUNTRY":"INDIA"}

    public static void main(String[] args) {
        JSONObject createUserJson = new JSONObject();
        createUserJson.put("NAME", "GOPAL");
        createUserJson.put("AGE", 25);
        createUserJson.put("COUNTRY", "INDIA");
       
        String jsonString =  JSONValue.toJSONString(createUserJson);
        System.out.println(jsonString); 
      
    }

2. JSON creation with Array

Requirement:  
{"NAME":"USER","AGE":25,"COUNTRY":"INDIA",
    "ADDRESS" : [ {"STREET":"xyz", "POSTAL CODE":"654321","CITY":"BANGALORE"} ,
                               {"STREET":"abc", "POSTAL CODE":"987654","CITY":"BANGALORE"}
                             ]                              
}


public static void main(String[] args) {
        JSONObject createUserJson = new JSONObject();
        createUserJson.put("NAME", "GOPAL");
        createUserJson.put("AGE", 25);
        createUserJson.put("COUNTRY", "INDIA");
        

        List<Map> jsonArray = new ArrayList<Map>();
        Map<String, String> streetXYZ = new HashMap<String, String>();
        streetXYZ.put("STREET", "xyz");
        streetXYZ.put("POSTAL CODE", "654321");
        streetXYZ.put("CITY", "BANGALORE");

        Map<String, String> streetABC = new HashMap<String, String>();
        streetABC.put("STREET", "xyz");
        streetABC.put("POSTAL CODE", "654321");
        streetABC.put("CITY", "BANGALORE");

        jsonArray.add(streetXYZ);
        jsonArray.add(streetABC);

        createUserJson.put("ADDRESS", jsonArray);
 

        String jsonString =  JSONValue.toJSONString(createUserJson);
        System.out.println(jsonString); 
      
    }

3. Parsing JSON String - Example is parsing above JSON created.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

private static void parsingJsonString(String jsonString) {
        JSONParser parser = new JSONParser();
        try {
            JSONObject jsonObject = (JSONObject)parser.parse(jsonString);
            String name = (String)jsonObject.get("NAME");
            System.out.println(name);
           
            JSONArray addressArray = (JSONArray)jsonObject.get("ADDRESS");
            for (int i = 0; i < addressArray.size(); i++) {
                Object arrayObj = parser.parse(addressArray.get(i).toString());
                JSONObject jsonArrayObject = (JSONObject)arrayObj;
                System.out.println("Street " + jsonArrayObject.get("STREET"));
                System.out.println("Postal Code " +
                                   jsonArrayObject.get("POSTAL CODE"));
                System.out.println("City " + jsonArrayObject.get("CITY"));
                System.out.println("-------------------------------------");
            }

        } catch (ParseException e) {
            e.getMessage();
        }
  
}

*Using Json-simple-1.1.1.jar

*Comments and feedback are most welcomed, Thanks.