gson 将classname作为 Package 对象包含在json中

zynd9foi  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(149)

我目前正在用java构建一个JSON,当调用POST端点时,它将被用作请求体。我需要构建到JSON中的类如下所示:

public class EmployeeImport {
    @SerializedName("Header")
    private final Header header;
    @SerializedName("Employees")
    private final List<Employee> employees;

    public EmployeeImport(final Header header,
                          final List<Employee> employees) {
        this.header = header;
        this.employees = employees;
    }

我使用GSON从这个类生成JSON:

private String generateJSONForImport(final Employee employee, final Header header) {
        final EmployeeImport employeeImport = new EmployeeImport(header, Arrays.asList(employee));

        final Gson gson = new Gson();
        final String json = gson.toJson(employeeImport);
        System.out.println(json);
    }

当打印JSON时,它看起来像这样:

{
  "Header": {
    "Date": "2021-01-14"
  },
  "Employees": [
    {
      "ValueOne": "lala",
      "ValueTwo": "lalala"
    }
  ]
}

但我需要JSON包含类“EmployeeImport”作为 Package 对象,如下所示:

{
    "EmployeeImport": {
        "Header": {
            "Date": "2021-01-13"
        },

        "Employees": [{
            "ValueOne": "lala",
            "ValueTwo": "lalala"
        }]
    }
}

我已经为此寻找了一个好的解决方案,我已经看到注解“@JsonTypeInfo”似乎可以解决这个问题,但这似乎只适用于jackson库。
有没有人知道一个好的解决方案,如何可以做到这一点与GSON库?

rhfm7lfc

rhfm7lfc1#

您可以创建该 Package 类,并将其用作您的EmployeeImport
在下面的示例中,我将现有的EmployeeImport类转换为一个名为EmployeeImportInner的内部类,并将其放置在EmployeeImport中:

public class EmployeeImport {

    @SerializedName("EmployeeImport")
    private EmployeeImportInner inner;

    public class EmployeeImportInner {

        @SerializedName("Header")
        private Header header;
        @SerializedName("Employees")
        private List<Employee> employees;

        public EmployeeImportInner(final Header header,
                final List<Employee> employees) {
            this.header = header;
            this.employees = employees;
        }

        // getters/setters not shown

    }

    // getter/setter not shown

}

你不必这样做-你可以有两个单独的类,如果你喜欢。
在我的例子中,我构建了外部对象,如下所示:

EmployeeImport employeeImport = new EmployeeImport();

final EmployeeImport.EmployeeImportInner employeeImportInner = 
        employeeImport.new EmployeeImportInner(header, employees);

employeeImport.setInner(employeeImportInner);

现在,您将在JSON中看到所需的外部对象名称。

相关问题