Thursday, 9 January 2014

Java Object To JSON and JSON to java Object

JSON is stand for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many Java applications started to throw away XML format and start using json as a new s data-interchange format. Java is all about object, often times, you need to convert an object into json format for data-interchange or vice verse.


Gson is google provided library that provide api to and form convertion of JSON and java object.
Gson API
  1. toJson() – For Java object to JSON 
  2. fromJson() – For JSON to Java object

Download : 

Link

Maven dependency


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

JSON Utility


 public final class JsonUtils {  
      private JsonUtils() {  
      }  
      public static <T> T getObject(final String jsonString, final Class<T> objectClass) {  
           Gson gson = new Gson();  
           return gson.fromJson(jsonString, objectClass);  
      }  
      public static String getString(final Object object) {  
           Gson gson = new Gson();  
           return gson.toJson(object);  
      }  
 }  

References
  1. Google Gson – http://code.google.com/p/google-gson/
  2. Json Official site – http://www.json.org/
  3. Json in Wiki – http://en.wikipedia.org/wiki/JSON

profile for Ashish Aggarwal at Stack Overflow, Q&A for professional and enthusiast programmers