重命名响应 dto 的字段。 Java、Spring

Rename fields in response dto. Java, Spring

我有以下问题。我想重命名 JSON 响应中的字段。在我的 DTO 字段中,定义为 camal 大小写。作为回应 json a 想使用带下划线的单独单词。我尝试使用 @JsonPropperty 注释,但它不起作用。我的 DTO class 如下:

package com.example.demo.dto.response;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;


import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Data
public class UserResponseDto {
    private String id;
    private String name;
    @JsonProperty("second_name")
    private String secondName;
    private String email;
    private String login;
    private String password;
    @JsonProperty("date_of_birth")
    private Date dateOfBirth;
    @JsonProperty("date_of_registration")
    private Date dateOfRegistration;
    private Set<RoleResponseDto> roles = new HashSet<>();
}

并且响应仍然是小写形式:

{
        "id": "d6c0873b-166b-4d6f-90b4-91d9f0dfa0a0",
        "name": "Simon",
        "secondName": "Wilder",
        "email": "myNewEmail@gmail.com",
        "login": "QMY",
        "password": "a$Lj3EctARwD34EInzmwsjjuTsKiOzKtI7Gf7pskUfxcPt1PNRDHF1m",
        "dateOfBirth": "1991-12-21T00:00:00.000+00:00",
        "dateOfRegistration": "2022-04-07T12:52:24.059+00:00",
        "roles": [
            {
                "id": "a9cc27ba-532a-456a-a9b5-ad14052190f8",
                "title": "ROLE_USER"
            },
            {
                "id": "684bf3b6-721d-494c-9c66-caeee44933d2",
                "title": "ROLE_ADMIN"
            }
        ]
    }

你有什么想法吗?或者它是一个错误,或者什么?到处都写着使用@JsonPropperty注解。

所以有两种方法可以做你想做的事,但首先要确保你在所有控制器方法上使用 @ResponseBody 或确保你的控制器 类 使用 @RestController

  1. 如果您希望整个应用程序在响应正文中使用下划线大小写,请将其添加到您的配置中:

Gson 方法

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(createGsonHttpMessageConverter());
        super.addDefaultHttpMessageConverters(converters);
    }

    @Bean
    public Gson createGson() {
        return new GsonBuilder().disableHtmlEscaping()
                .serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();
    }

    @Bean
    public GsonHttpMessageConverter createGsonHttpMessageConverter() {
        GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();

        gsonConverter.setGson(createGson());

        return gsonConverter;
    }
}

Reference

杰克逊法

spring.jackson.property-naming-strategy=SNAKE_CASE

Reference:

  1. 如果你想在单个 DTO 上使用它,那么你可以使用

    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Refercences: