Vinod Jayachandran
Vinod Jayachandran

Reputation: 3898

Convert Java Object to JSON using Groovy JsonBuilder

I am trying to convert Java Object to JSON using Groovy JsonBuilder

Java POJO Class

public class Employee {

    String name;

    int age;

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Groovy Script

Employee employee = new Employee();
employee.name="Vinod"
employee.age=24

println new JsonBuilder( employee ).toPrettyString()

Output

{

}

I am not sure if I am using JsonBuilder incorrectly. Please help

Upvotes: 4

Views: 2808

Answers (1)

jalopaba
jalopaba

Reputation: 8119

Since you are using a Java POJO, you need to add the getters for the two properties you have, i.e., public String getName() and public String getAge().

The JsonBuilder leverages DefaultGroovyMethods.getProperties to get object properties. If you don't add the aforementioned getters, it does not find any properties and therefore the resulting JSON is empty.

So that:

Employee.java

public class Employee {
    String name;
    int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return String.format("Employee{name=%s, age=%d}", name, age);
    }
}

If you use a POGO instead (Plain Old Groovy Object), getters are added by default for each property, so it works out of the box:

Upvotes: 4

Related Questions