如何在spring restful中更改控制器后的值

w7t8yxp5  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(300)

我想在之后更改数据 @RestController Spring 上课
我需要根据指定的语言更改字段数据。
例子:
枚举:

public enum Gender {
    WOMAN, MAN, OTHER
}

控制器:

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public User get(@PathVariable Long id) throws Exception {

    log.debug("Entering get( id={} )", id);

    User user = null;

    try {
        user = UserService.get(id);

    } catch (Exception e) {
        log.debug("Error occurred in get().", e);

        throw e;
    }

    return user;
}

此输出:

{
    fisrtName: 'john',
    lastName: 'doe',
    gender: 'man'
}

更改此输出:

{
    fisrtName: 'john',
    lastName: 'doe',
    gender: 'homme'
}
jk9hmnmh

jk9hmnmh1#

我假设user.gender是一个枚举。然后,您可以向jsonMap器添加自定义序列化程序和反序列化程序(最好是jackson)。

@JsonComponent
public class TranslatedGenderJsonComponent {

   public static class TranslatedGenderSerializer extends StdSerializer<Gender> {

        public TranslatedGenderSerializer () {
            super(Gender.class);
        }

        public void serialize(
          Gender gender, JsonGenerator generator, SerializerProvider provider) 
          throws IOException, JsonProcessingException {

            String translatedGender = myTranslateFunction(gender);

            generator.writeString(translatedGender );
        }
    }   

    public static class TranslatedGenderDeserializer extends StdDeserializer<Gender> {

        public TranslatedGenderDeserializer () {
            super(Gender.class);
        }

       public Gender deserialize(JsonParser jp, DeserializationContext ctxt) 
          throws IOException, JsonProcessingException {

            JsonToken currentToken = jp.getCurrentToken();      
            if (currentToken.equals(JsonToken.VALUE_STRING)) {             
                String text jp.getText().trim();
                Gender gender = myInverseTranslateFunction(text);
                return gender;
            } else if (currentToken.equals(JsonToken.VALUE_NULL)) {
                return getNullValue();
            } else {        
                throw ctxt.mappingException(Gender.class);
            }
        }
    }
}

这段代码没有经过测试,它只是在浏览器中编写的(我对反序列化程序/解析器代码很不确定。)但我希望它能引导您找到解决方案。

zsohkypk

zsohkypk2#

我改了密码:
控制器:

@Autowired
GlobalMassengerAdvice globalMassenger;

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public User get(@PathVariable Long id) throws Exception {

    log.debug("Entering get( id={} )", id);

    User user = null;

    try {
        user = userService.get(id);

        String value = globalMassenger.getMessage(user.getGender().name());

        user.setGender( value );

    } catch (Exception e) {
        log.debug("Error occurred in get().", e);

        throw e;
    }

    return user;
}

我添加了新类(globalAssengerAdvice):

@ControllerAdvice
public class GlobalMassengerAdvice {

    @Autowired
    private MessageSource messageSource;

    public String getMessage(final String messageKey, final Object... messageParameters) {
        Locale locale = LocaleContextHolder.getLocale();
        String result = null;
        try {
            result = messageSource.getMessage(messageKey, messageParameters, locale);
        } catch (NoSuchMessageException e) {
            result = messageKey;
        }
        return result;
    }

}

相关问题