有没有办法从具有对象组合的 pojo 自动生成扁平的 pojo

Is there a way to auto generate a flatten pojo from a pojo with object composition

我需要将文档存储到 Elasticsearch 索引中,因此我定义了一个映射。从我的 java 客户端,我需要为它提供看起来像 Compony class 的 pojo。它有很多重复的值。我可以使用对象组合模式来解决这个问题,但 Elasticsearch 无法处理这种结构,因此它需要一个扁平化结构。

class Company {
    private String postalstreetName;
    private String postalHouseNumer;
    private String postalHouseLetter;
    private String postalHouseNumberAddition;
    private String postalZipCode;
    private String postalCity;
    private String postalCountry;

    private String visitorstreetName;
    private String visitorHouseNumer;
    private String visitorHouseLetter;
    private String visitorHouseNumberAddition;
    private String visitorZipCode;
    private String visitorCity;
    private String visitorCountry;

    private String establishmentstreetName;
    private String establishmentHouseNumer;
    private String establishmentHouseLetter;
    private String establishmentHouseNumberAddition;
    private String establishmentZipCode;
    private String establishmentCity;
    private String establishmentCountry;
}

我实际上想要像下面这样的 pojo,并且以某种方式自动生成具有相同命名结构的上面的 pojo。

class Address {
    private String streetName;
    private String houseNumer;
    private String houseLetter;
    private String houseNumberAddition;
    private String zipCode;
    private String city;
    private String country;
}
class Company {
    private Address postalAddress;
    private Address visitorAddress;
    private Address establishmentAddress;
}

有人知道这样的事情是否可能,从一个对象组合的 pojo 自动生成一个扁平的 pojo,所有字段都有一个名称前缀?

我找到了问题的解决方案。 Elasticsearch 期望 json 对象具有我在第一个示例中的结构。所以我所做的是将 @JsonUnwrapped 添加到具有前缀值的字段中,所以我的公司 class 看起来像这样:

class Company {
    @JsonUnwrapped(prefix = "postal")
    private Address postalAddress;
    @JsonUnwrapped(prefix = "visitor")
    private Address visitorAddress;
    @JsonUnwrapped(prefix = "Establishment")
    private Address establishmentAddress;
}

结果将是:

{
  "postalStreetName":"",
  "postalHouseNumer":"",
  "postalHouseLetter":"",
  "postalHouseNumberAddition":"",
  "postalCity":"",
  "postalCountry":"",
  "visitorStreetName":"",
  "visitorHouseNumer":"",
  "visitorHouseLetter":"",
  "visitorHouseNumberAddition":"",
  "visitorCity":"",
  "visitorCountry":"",
  "establishmentStreetName":"",
  "establishmentHouseNumer":"",
  "establishmentHouseLetter":"",
  "establishmentHouseNumberAddition":"",
  "establishmentCity":"",
  "establishmentCountry":""
}    

所以我不需要以某种方式神奇地创建那些 pojo,因为 jackson 可以创建我需要的 json 文件。