By
using google gson jar, we can easily convert json to java and java to
json conversion. You can download it from
'http://code.google.com/p/google-gson/'.
Example
public class Employee { String firstName; String lastName; int age; Employee(String firstName, String lastName, int age){ this.firstName = firstName; this.lastName = lastName; this.age = age; } }
import com.google.gson.Gson; public class JsonEx { public static void main(String[] args) { Employee obj = new Employee("Krishna", "Gurram", 26); Gson gson = new Gson(); System.out.println("Converting employee object to json format"); String json = gson.toJson(obj); System.out.println("Json format is"); System.out.println(json); System.out.println("\nConverting json data to Employee object"); Employee emp = gson.fromJson(json, Employee.class); System.out.println("Employee name " + emp.firstName); System.out.println("Employee last name " + emp.lastName); System.out.println("Employee age " + emp.age); } }
Output
Converting employee object to json format Json format is {"firstName":"Krishna","lastName":"Gurram","age":26} Converting json data to Employee object Employee name Krishna Employee last name Gurram Employee age 26
No comments:
Post a Comment