java-将复杂的Java对象转换为json

时间:2019-02-20 12:53:36

标签: java json

我有一个像下面这样的课程-

public class Person {   
    private String firstName;
    private String lastname;
    private Address address;

   // getters and setters
}

public class Address {
    private String streetName;
    private String postCode;
    private Contact contact;
   // getters and setters
}

public class Contact {
    private String telephone;
    private String email;
   // getters and setters
}

我正在使用这样的gson库将其转换为json对象-

Gson gson = new GsonBuilder()
                    .serializeNulls()
                    .setPrettyPrinting()
                    .create();
        System.out.println(gson.toJson(new Person()));

然后我得到json like-

{
  "firstName": null,
  "lastname": null,
  "address": null
}

但是我正在寻找json之类的

{
  "firstName": null,
  "lastname": null,
  "address": {
      "streetName": null,
      "postCode": null,
      "contact": {
         "telephone": null,
         "email": null
       }
   }
}

有人可以帮助我实现这一目标吗?

3 个答案:

答案 0 :(得分:4)

我认为您获得的结果JSON是预期的JSON:new Person().address字段为空(如果您未在Person的构造函数中对其进行初始化),因此将其序列化为{{1 }}。

您要搜索的输出对应于类似的序列化

null

这是Person p = new Person(); Address a = new Address(); a.setContact(new Contact()); p.setAddress(a); gson.toJson(p); 的实例,不同于Person ...

答案 1 :(得分:1)

只需将您的Person类更改为

public class Person {   
    private String firstName;
    private String lastname;
    private Address address;

    public Person() {
        this(new Address());
    }

    public Person(Address address) {
        this.address = address;
    }

    // getters and setters
}

否则没有地址,因此JSON中的

答案 2 :(得分:0)

您应该将地址作为对象添加到您的人员类别中,而不是null。

修改您的代码 -向Person添加构造函数以地址对象作为参数

  public class Person {
        private String firstName;
        private String lastname;
        private Address address;

        public Person(Address address) {
            this.address=address;
        }

        // getters and setters
    }

然后用这一行替换打印行:

System.out.println(gson.toJson(new Person(new Address())));