gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:33:29 25 4
gpt4 key购买 nike

在尝试将包含 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.

关于json - 使用 Gson 将具有 under_score 的 JSON 属性转换为具有 lowerCamel 属性的 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67405683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com