使用 Gson 将具有 under_score 的 JSON 属性转换为具有 lowerCamel 属性的 DTO

Convert JSON properties with under_score to DTO with lowerCamel properties using Gson

我在尝试将包含 under_score 属性的 JSON 响应转换为具有 lowerCamelCase 属性的 DTO 时遇到了一些困难。

JSON 例如:

{
      "promoted_by": "",
      "parent": "",
      "caused_by": "jenkins",
      "watch_list": "prod",
      "u_automation": "deep",
      "upon_reject": "cancel"
}

例如DTO:

@Data
public class TicketDTO {

    private String promotedBy;
    private String parent;
    private String causedBy;
    private String watchList;
    private String uAutomation;
    private String uponReject;
}

映射器:

@Mapper(componentModel = "spring")
public interface ITicketMapper {

    default TicketDTO toDTO(JsonObject ticket) {
        Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .create();

        return gson.fromJson(incident, TicketDTO.class);
    }

}

这个例子当然是行不通的,我想知道是否可以用 Gson 进行这种转换。

感谢您的帮助。

你应该使用LOWER_CASE_WITH_UNDERSCORES

Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_). Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

  • someFieldName ---> some_field_name
  • someFieldName ---> _some_field_name
  • aStringField ---> a_string_field
  • aURL ---> a_u_r_l

setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)

UPPER_CAMEL_CASE用于不同的目的

Using this naming policy with Gson will ensure that the first "letter" of the Java field name is capitalized when serialized to its JSON form.