4

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

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.