Friday 14 November 2014

Convert Java Object to JSON


“com.google.gson.Gson” class provides toJson() method to convert java object to JSON.

Gson gson = new Gson();
String json = gson.toJson(emp);

Above code converts Employee object emp to JSON string.

public class Organization {
    private String name;
    private float yrsOfExperience;

    Organization(String name, float yrsOfExperience){
        this.name = name;
        this.yrsOfExperience = yrsOfExperience;
    }

    public String getName() {
        return name;
    }

    public float getYrsOfExperience() {
        return yrsOfExperience;
    }

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

    public void setYrsOfExperience(float yrsOfExperience) {
        this.yrsOfExperience = yrsOfExperience;
    }
    
}


import java.util.*;

public class Employee {
    private List<Organization> org = new ArrayList<Organization> ();
    private String firstName;
    private String lastName;
    private double salary;

    Employee(String firstName, String lastName, double salary, List<Organization> org){
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
        this.org = org;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public List<Organization> getOrg() {
        return org;
    }

    public double getSalary() {
        return salary;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setOrg(List<Organization> org) {
        this.org = org;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    
}


import java.util.*;
import com.google.gson.Gson;

public class JavaToJSON {
    public static void main(String args[]){
        List<Organization> organizations = new ArrayList<Organization> ();
        Organization o1 = new Organization("Honeywell", 2.2f);
        Organization o2 = new Organization("IBM", 1.8f);
        organizations.add(o1);
        organizations.add(o2);

        Employee emp = new Employee("Krishna", "Hari", 80000, organizations);

        Gson gson = new Gson();
        String json = gson.toJson(emp);

        System.out.println(json);
    }
}


Output
{"org":[{"name":"Honeywell","yrsOfExperience":2.2},{"name":"IBM","yrsOfExperience":1.8}],"firstName":"Krishna","lastName":"Hari","salary":80000.0}




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment