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.

Useful groovy expressions and resuable Java code in ADF

---------- Groovy Expressions ----------

1. Generate sequence using groovy.

(new oracle.jbo.server.SequenceImpl
("SEQUENCE_NAME",adf.object.getDBTransaction())).getSequenceNumber()

2. Fetching record of View Accessor in any attribute of View Object.

Suppose View accessor name is DepartmentVA

if (null!= DepartmentVA.first())
return DepartmentVA.first().getAttribute('DepartmentName');


2. Reusable JAVA code

import javax.el.ExpressionFactory;
import javax.faces.context.FacesContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.binding.OperationBinding;

    /**
     * This methos returns the operation bindings of the passed method name
     * @param operation name
     * @return
     */
    public static OperationBinding getOperBindings(String operation) {
        OperationBinding oper = null;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExpressionFactory exp = facesContext.getApplication().getExpressionFactory();
        DCBindingContainer bindingContainer =
            (DCBindingContainer) exp.createValueExpression(facesContext.getELContext(), "#{bindings}",
                                                           DCBindingContainer.class).getValue(facesContext.getELContext());
        oper = bindingContainer.getOperationBinding(operation);
        System.out.println("Exit - [Util : getOperBindings]");
        return oper;
    }

----------------------------------------------------------------------------------------------------------------------
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;

    /**
     * Programmatic evaluation of EL.
     * @param el EL to evaluate
     * @return Result of the evaluation
     */

    public static Object evaluateEL(String el) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);
        return exp.getValue(elContext);
    }

----------------------------------------------------------------------------------------------------------------------
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;

     /**
      * Sets a value into an EL object.
      * Provides similar functionality to the af:setActionListener tag, except the from is not an EL.
      * You can get similar behavior by using the following...
      * setEL(to, evaluateEL(from))     *
      * @param el EL object to assign a value
      * @param val Value to assign
      */

     public static void setEL(String el, Object val) {
         FacesContext facesContext = FacesContext.getCurrentInstance();
         ELContext elContext = facesContext.getELContext();
         ExpressionFactory expressionFactory =
             facesContext.getApplication().getExpressionFactory();
         ValueExpression exp =
             expressionFactory.createValueExpression(elContext, el,
                                                     Object.class);
         exp.setValue(elContext, val);
     }


----------------------------------------------------------------------------------------------------------------------
import oracle.adf.model.BindingContext;
import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;


      /**
       * Method will be used to execute the BC operations
       * such as : Commit, Rollback, Execute etc.
       * @param operation
       */

      public static OperationBinding commitUsingOperationBinding(String operation) {
          BindingContainer bindings =
              BindingContext.getCurrent().getCurrentBindingsEntry();
          OperationBinding oper = (OperationBinding)bindings.get(operation);
          oper.execute();
          return oper;
      }

----------------------------------------------------------------------------------------------------------------------
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.jbo.RowSetIterator;

    /**
     * Method to retrieve row set iterator by iterator name
     * @param iteratorName
     * @return RowSetIterator
     */

    public static RowSetIterator getRowSetIter(String iteratorName) {
        DCBindingContainer dcBindings =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding iteratorBinding =
            (DCIteratorBinding)dcBindings.get(iteratorName);
        RowSetIterator rowSetIterator =
            iteratorBinding.getViewObject().createRowSetIterator(null);
        rowSetIterator.reset();
        return rowSetIterator;
    }

---------------------------------------------------------------------------------------------------------------------- 
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

     /**
      * Refresh page from root
      */

     public static void rootRefresh() {
         FacesContext facesContext = FacesContext.getCurrentInstance();
         String refreshpage = facesContext.getViewRoot().getViewId();
         ViewHandler viewHandler =
             facesContext.getApplication().getViewHandler();
         UIViewRoot viewroot =
             viewHandler.createView(facesContext, refreshpage);
         viewroot.setViewId(refreshpage);
         facesContext.setViewRoot(viewroot);
     }

----------------------------------------------------------------------------------------------------------------------

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import javax.servlet.http.HttpServletRequest;

    /**
     *
How to navigate to the mentioned URL in Application
     * @param url
     */

   
public static void navigateTO(String url) {
        String urlToNavigate = url;
        ExternalContext ectx =
            FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest)ectx.getRequest();
        String completeUrl = null;
        completeUrl = request.getContextPath() + urlToNavigate;
        try {
            ectx.redirect(completeUrl);
        } catch (IOException e) {
          
        }
    } 



*Comments and feedback are most welcomed, Thanks.