简体   繁体   English

使用Groovy JsonBuilder将Java Object转换为JSON

[英]Convert Java Object to JSON using Groovy JsonBuilder

I am trying to convert Java Object to JSON using Groovy JsonBuilder 我正在尝试使用Groovy JsonBuilder将Java Object转换为JSON

Java POJO Class Java POJO类

public class Employee {

    String name;

    int age;

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

Groovy Script Groovy脚本

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. 我不确定我是否错误地使用JsonBuilder。 Please help 请帮忙

Since you are using a Java POJO, you need to add the getters for the two properties you have, ie, public String getName() and public String getAge() . 由于您使用的是Java POJO,因此需要为您拥有的两个属性添加getter ,即public String getName()public String getAge()

The JsonBuilder leverages DefaultGroovyMethods.getProperties to get object properties. JsonBuilder利用DefaultGroovyMethods.getProperties来获取对象属性。 If you don't add the aforementioned getters, it does not find any properties and therefore the resulting JSON is empty. 如果您不添加上述getter,则它找不到任何属性,因此生成的JSON为空。

So that: 以便:

Employee.java 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: 如果您使用POGO(Plain Old Groovy Object),默认情况下会为每个属性添加getter ,因此它开箱即用:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM