Convert JSON to Java Object using Google Gson library


In earlier tutorial we have seen how to convert Java Object to JSON. Lets take same example and try to convert JSON to Java Object using Google Gson library. The JSON output of earlier tutorial will be saved in file and will use same JSON file for this sample demo.

pom.xml

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>


 Company.java

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

public class Company {

 private List<String> employeeNames = new ArrayList<String>();
 
 private String companyName;
 
 private String companyAddress;
 
 private String domain;

 public List<String> getEmployeeNames() {
  return employeeNames;
 }

 public void setEmployeeNames(List<String> employeeNames) {
  this.employeeNames = employeeNames;
 }

 public String getCompanyName() {
  return companyName;
 }

 public void setCompanyName(String companyName) {
  this.companyName = companyName;
 }

 public String getCompanyAddress() {
  return companyAddress;
 }

 public void setCompanyAddress(String companyAddress) {
  this.companyAddress = companyAddress;
 }

 public String getDomain() {
  return domain;
 }

 public void setDomain(String domain) {
  this.domain = domain;
 } 
}


 company.json File:

{"employeeNames":["Steve","Jobs","Gates","Gary"],"companyName":"ABC Infotech","companyAddress":"Bangalore, India","domain":"Media"}


 JSONTesting.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

public class JSONTesting {
 
 public static void main(String[] args) {
  
  try {
  
   BufferedReader br = new BufferedReader( new FileReader("c:\\ASIC\\company.json"));
  
   Company obj = new Gson().fromJson(br, Company.class);

   System.out.println("Company Name    : "+obj.getCompanyName());
   System.out.println("Employee Names  : " + obj.getEmployeeNames());
   System.out.println("Company Address : "+obj.getCompanyAddress());
   System.out.println("Domain          : "+obj.getDomain());
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


 OUTPUT:

Convert JSON to Java Object using Google Gson library


Convert Java Object to JSON using Google Gson library

In this tutorial lets see how to convert Java Object to JSON using Google Json library. Its quite very easy and just by toJson() method we can convert to JSON. Lets see simple example for converting Java Object to JSON along with maven dependency for Google Gson.
Covert Java Object to JSON using Google Gson library


pom.xml

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>


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

public class Company {

 private List<String> employeeNames = new ArrayList<String>();
 
 private String companyName;
 
 private String companyAddress;
 
 private String domain;

 public List<String> getEmployeeNames() {
  return employeeNames;
 }

 public void setEmployeeNames(List<String> employeeNames) {
  this.employeeNames = employeeNames;
 }

 public String getCompanyName() {
  return companyName;
 }

 public void setCompanyName(String companyName) {
  this.companyName = companyName;
 }

 public String getCompanyAddress() {
  return companyAddress;
 }

 public void setCompanyAddress(String companyAddress) {
  this.companyAddress = companyAddress;
 }

 public String getDomain() {
  return domain;
 }

 public void setDomain(String domain) {
  this.domain = domain;
 } 
}

JSONTesting.java
import com.google.gson.Gson;

public class JSONTesting {
 
    public static void main( String[] args ) {
     
     Company obj = new Company();
     
     obj.getEmployeeNames().add("Steve");
     obj.getEmployeeNames().add("Jobs");
     obj.getEmployeeNames().add("Gates");
     obj.getEmployeeNames().add("Gary");
     
     obj.setCompanyName("ABC Infotech");
     obj.setCompanyAddress("Bangalore, India");
     obj.setDomain("Media");
     
     Gson gson = new Gson();
     
        //Converts Java Object to JSON
     String json = gson.toJson(obj);
     
     System.out.println(json);
    }
}


OUTPUT:


{"employeeNames":["Steve","Jobs","Gates","Gary"],"companyName":"ABC Infotech","companyAddress":"Bangalore, India","domain":"Media"}

java.util.Date to java.sql.Date with timestamp

java.sql.Date() class mainly used in JDBC API. If we need to set date value or need to get date from JDBC result-set then we need to go for java.sql.Date(). Actually java.sql.Date() class extends java.util.Date() class and we can do all operations which we used with java.util.Date() class. Only one main difference between these classes are java.sql.Date() class hold only date and timestamp. Even if try to call methods like getHours(), getMinutes() and getSeconds() which will throw exception like

java.lang.IllegalArgumentException
 at java.sql.Date.getHours(......)

In that case if we need date along with timestamp to deal with JDBC API we can use java.sql.timestamp() class. A thin wrapper around java.util.Date() that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.

Now lets see simple example to get current date and time in java.sql.Date() and convert to java.sql.Date() and java.sql.Timestamp()


public class DateTimeTesting {

 public static void main(String[] args) {
  
  java.util.Date date = new java.util.Date();
  System.out.println("Util DATE       : "+date);
  
  java.sql.Date sqlDate = new java.sql.Date(date.getTime());
  System.out.println("SQL DATE        : "+sqlDate);
  
  java.sql.Timestamp sqlDateTime = new java.sql.Timestamp(date.getTime());
  System.out.println("SQL DATE & TIME : "+sqlDateTime);
 }
}

OUTPUT:

java.util.Date to java.sql.Date with timestamp



Try-with-Resources in Java 7

The try-with-resources statement is a try statement that declares one or more resources within try statement. A resource(s) is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement and finally block is no more required when we use it.
Try-with-Resources in Java 7


If we see earlier to Java 7 like which we are familiar with try-catch-finally block. Here if exception thrown from try block, then finally block will be executed. Suppose if finally block also thrown with exception then try block would probably be more relevant to propagate exception than finally block.

Lets see simple example with both try-catch-finally and try-with-resources.

try-catch-finally example to open a file and to read line by line.


public class TryCatchFinallyTest {
 
 public static void main(String[] args) {
  
  FileInputStream fis = null;
  BufferedReader br = null;
  
  try{
   fis = new FileInputStream("C:\\textfile.txt");
   br = new BufferedReader(new InputStreamReader(fis));
   
   String line = null;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
   
  }catch(IOException ex){
   ex.printStackTrace();
  }finally{
   if(fis != null){
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }   
   }
   if(br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }   
 } 
}


try-with-resources example to open a file and to read line by line.

public class TryWithResourceTest {
 
 public static void main(String[] args) {
  
  try(FileInputStream fis = new FileInputStream("C:\\textfile.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fis))
    ){
   
   String line = null;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }   
  }  
 } 
}

If we see both examples we can find the difference in code. In Java 7 we have more simple and less code compared to earlier try-catch-finally block. Moreover from advantage side opened resources will be closed automatically once they are out of block, but in earlier we need to close explicitly. 


Spring: Data access using JdbcDaoSupport

Similar to JDBCTemplate by extending JdbcDaoSupport classes we can achieve JBDC dataaccess and just need to inject data source into EmpDaoImpl Objects through configuration file. Rest will be taken care by Spring.

In our earlier tutorials we have seen about Spring JDBC and JDBCTemplate examples. Lets take same example class and will extend JdbcDaoSupport class.

pom.xml remains same

Employee.java remains same

EmpDao.java remains same

MyTestClass.java

package com.app;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.dao.EmpDao;
import com.app.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring-jdbc.xml");

  EmpDao object = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee(143, "Bill", "Director");
  
  object.insert(emp);
  
  appContext.close();
 }
}


EmpDaoImpl.java

package com.app.dao;


import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.app.model.Employee;

public class EmpDaoImpl extends JdbcDaoSupport implements EmpDao {

 public void insert(Employee emp) {
  
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  
  getJdbcTemplate().update(query, new Object[] { emp.getId(), emp.getEmpName(), emp.getDesignation() });
 }
}


OUTPUT:

Spring: Data access with JdbcDaoSupport



Spring: Data access with JDBCTemplate

Spring provides a template class called JdbcTemplate that makes it easy to work with SQL relational databases and JDBC. Most JDBC code is mired in resource acquisition, connection management, exception handling, and general error checking that is wholly unrelated to what the code is meant to achieve. The JdbcTemplate takes care of all of that for you. All you have to do is focus on the task at hand.

In our earlier tutorial we have seen about Spring JDBC with simple example. Lets take same example for this tutorial and will implement separate method called insertByJDBCTemplate() which uses Spring JDBCTemplate to insert a record.

pom.xml remains same

Employee.java remains same

EmpDao.java

package com.app.dao;

import com.app.model.Employee;

public interface EmpDao {

 public void insert(Employee emp);
 public void insertByJDBCTemplate(Employee emp);
 
}


EmpDaoImpl.java

package com.app.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.app.model.Employee;

public class EmpDaoImpl implements EmpDao {

 
 private DataSource dataSource;
 private JdbcTemplate jdbcTemplate;
 
 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }
  
 public void insert(Employee emp) {
 
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  Connection con = null;
 
  try {
   con = dataSource.getConnection();
   PreparedStatement ps = con.prepareStatement(query);
   ps.setInt(1, emp.getId());
   ps.setString(2, emp.getEmpName());
   ps.setString(3, emp.getDesignation());
   ps.executeUpdate();
   ps.close();
 
  } catch (SQLException e) {
   throw new RuntimeException(e);
 
  } finally {
   if (con != null) {
    try {
     con.close();
    } catch (SQLException e) {}
   }
  }  
 }
 
 
 
 public void insertByJDBCTemplate(Employee emp) {
  
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  
  jdbcTemplate = new JdbcTemplate(dataSource);
   
  jdbcTemplate.update(query, new Object[] { emp.getId(), emp.getEmpName(), emp.getDesignation() });
 }
}


MyTestClass.java

package com.app;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.dao.EmpDao;
import com.app.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring-jdbc.xml");

  EmpDao object = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee(10011, "Steve", "CEO");
  
  //object.insert(emp);
  object.insertByJDBCTemplate(emp);
  
  appContext.close();
 }
}


OUTPUT:

Spring: Data access with JDBCTemplate



Java Interview Questions - 8

In our earlier tutorial we have seen lot of Java interview questions and sample programs. In this tutorial we see similar set of interview questions and answers.


What is the purpose of the System class?


Which TextComponent method is used to set a TextComponent to the read-only state?


How are the elements of a CardLayout organized?


Is &&= a valid Java operator?


Name the eight primitive Java types.


Java Interview Questions - 7

Which class should you use to obtain design information about an object?


What is the relationship between clipping and repainting?


Is "abc" a primitive value?


What is the relationship between an event-listener interface and an event-adapter class?


What restrictions are placed on the values of each case of a switch statement?


What modifiers may be used with an interface declaration?


Is a class a subclass of itself?


What is the highest-level event class of the event-delegation model?


What event results from the clicking of a button?


How can a GUI component handle its own events?


What is the difference between a while statement and a do statement?


How are the elements of a GridBagLayout organized?


What advantage do Java's layout managers provide over traditional windowing systems?


What is the Collection interface?


What modifiers can be used with a local inner class?


What is the difference between static and non-static variables?


What is the difference between the paint() and repaint() methods?


What is the purpose of the File class?


Can an exception be rethrown?


Which Math method is used to calculate the absolute value of a number?


How does multithreading take place on a computer with a single CPU?


When does the compiler supply a default constructor for a class?


When is the finally clause of a try-catch-finally statement executed?


Which class is the immediate superclass of the Container class?


If a method is declared as protected, where may the method be accessed?


How can the Checkbox class be used to create a radio button?


Which non-Unicode letter characters may be used as the first character of an identifier?


What restrictions are placed on method overloading?


What happens when you invoke a thread's interrupt method while it is sleeping or waiting?


What is casting?


What is the return type of a program's main() method?


Name four Container classes.


What is the difference between a Choice and a List?


What class of exceptions are generated by the Java run-time system?


What class allows you to read objects directly from a stream?


What is the difference between a field variable and a local variable?


Under what conditions is an object's finalize() method invoked by the garbage collector?


How are this() and super() used with constructors?


What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?


What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?


How is it possible for two String objects with identical values not to be equal under the == operator?


Why are the methods of the Math class static?


What Checkbox method allows you to tell if a Checkbox is checked?


What state is a thread in when it is executing?


What are the legal operands of the instanceof operator?


How are the elements of a GridLayout organized?


What an I/O filter?


If an object is garbage collected, can it become reachable again?


What is the Set interface?


What classes of exceptions may be thrown by a throw statement?


What are E and PI?


Are true and false keywords?


What is a void return type?


What is the purpose of the enableEvents() method?


What is the difference between the File and RandomAccessFile classes?


What happens when you add a double value to a String?


What is your platform's default character encoding?


Which package is always imported by default?


What interface must an object implement before it can be written to a stream as an object?


How are this and super used?


What is the purpose of garbage collection?


What is a compilation unit?


What interface is extended by AWT event listeners?


What restrictions are placed on method overriding?


How can a dead thread be restarted?


What happens if an exception is not caught?


What is a layout manager?


Which arithmetic operations can result in the throwing of an ArithmeticException?


What are three ways in which a thread can enter the waiting state?


Can an abstract class be final?


What is the ResourceBundle class?


What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?


What is numeric promotion?


What is the difference between a Scrollbar and a ScrollPane?


What is the difference between a public and a non-public class?


To what value is a variable of the boolean type automatically initialized?


Can try statements be nested?


What is the difference between the prefix and postfix forms of the ++ operator?


What is the purpose of a statement block?


What is a Java package and how is it used?


What modifiers may be used with a top-level class?


What are the Object and Class classes used for?


How does a try statement determine which catch clause should be used to handle an exception?


Can an unreachable object become reachable again?


When is an object subject to garbage collection?


What method must be implemented by all threads?


What methods are used to get and set the text label displayed by a Button object?


Which Component subclass is used for drawing and painting?


What are synchronized methods and synchronized statements?


What are the two basic ways in which classes that can be run as threads may be defined?


What are the problems faced by Java programmers who don't use layout managers?


What is the difference between an if statement and a switch statement?


What is the List interface?