Wednesday 9 January 2019

Groovy: Convert json to object and object to json


Below statement converts java object to json string.
String json = new JsonBuilder(person).toPrettyString();

Below statement converts json string to java object.
Person person = new JsonSlurper().parseText(json);

Find the below working application.

JsonConverter.groovy
import java.util.HashMap;
import java.util.Map;

import groovy.json.JsonBuilder;
import groovy.json.JsonSlurper;

public class Person {

 private String firstName;
 private String lastName;

 /* Key is organization and value is designation */
 private Map < String, String > jobRoles;

 public String getFirstName() {
  return firstName;
 }

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

 public String getLastName() {
  return lastName;
 }

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

 public Map < String, String > getJobRoles() {
  return jobRoles;
 }

 public void setJobRoles(Map < String, String > jobRoles) {
  this.jobRoles = jobRoles;
 }

 @Override
 public String toString() {
  return "Person [firstName=" + firstName + ", lastName=" + lastName + ", jobRoles=" + jobRoles + "]";
 }

}

Person person = new Person();

Map < String, String > jobRoles = new HashMap < > ();
jobRoles.put("ABC Org", "Software Engineer");
jobRoles.put("XYZ Corp", "Architect");

person.setFirstName("Ram");
person.setLastName("Gurram");
person.setJobRoles(jobRoles);

String json = new JsonBuilder(person).toPrettyString();
System.out.println(json);

Person person2 = new JsonSlurper().parseText(json);
System.out.println(person2);


Output

{
    "jobRoles": {
        "ABC Org": "Software Engineer",
        "XYZ Corp": "Architect"
    },
    "firstName": "Ram",
    "lastName": "Gurram"
}
Person [firstName=Ram, lastName=Gurram, jobRoles=[ABC Org:Software Engineer, XYZ Corp:Architect]]



No comments:

Post a Comment