相关问题

Spring @ResponseBody Jackson JsonSerializer with JodaTime

Usage of @JsonSerialize and JsonSerializer

问题

我有这个枚举:

@JsonSerialize(using = JSONI18NSerializer.class)
public enum Status implements EnumOption {

    SOMETHING("translate.key,something"),
    ELSE("translate.key.else");

    private String status;

    private Status(final String status) {
        this.status = status;
    }


    @Override
    public String getDescription() {

        ReloadableResourceBundleMessageSource bundle =
            (ReloadableResourceBundleMessageSource) ContextLoader.getCurrentWebApplicationContext()
            .getBean("messageSource");

        Locale locale = LocaleContextHolder.getLocale();

        return bundle.getMessage(this.status, null, locale).toString();
    }
}


这实现了一个简单的接口:

public interface EnumOption {
    public String getDescription();
}


我写了这个自定义的JsonSerializer:

public class JSONI18NSerializer extends JsonSerializer<EnumOption> {
    @Override
    public void serialize(
            EnumOption object,
            JsonGenerator generator,
            SerializerProvider provider)
    throws IOException, JsonProcessingException {

          generator.writeStartObject();
          generator.writeFieldName("key");
          generator.writeString(object.toString());
          generator.writeFieldName("status");
          generator.writeString(object.getDescription());
          generator.writeEndObject();
     }
}




我想念什么?通过在控制器上使用@ResponseBody,我得到了带有简单{status:"translation of something"}的JSON,但我需要{status : {key:"something" , status : "description of something"}}

我是否必须在其他地方声明自定义序列化程序?是否有更好的方法来满足我的需求?

我正在使用Spring 4.1.7和Jackson 2.5.1并询问1.9.13

感谢您的帮助!!

编辑
这是控制器方法:

 @RequestMapping(value = "/search", method = RequestMethod.GET)
 @ResponseBody
    public List<Config> getAll(final ModelMap model) {
    return this.configService.searchConfig();

}


状态枚举是Config类的属性,该属性是:

 @Document
 public class Config {

    private Status status;

    public Status getStatus() {
        return this.status;
    }
    public void setStatus(final Status status) {
        this.status = status;
    }
}

最佳答案

尝试一下,我认为您正在将自定义输出的生成与JsonSerializer

public class JSONI18NSerializer extends JsonSerializer<EnumOption> {
    @Override
    public void serialize(
            EnumOption object,
            JsonGenerator generator,
            SerializerProvider provider)
            throws IOException, JsonProcessingException {
        generator.writeStartObject();
        generator.writeFieldName("status");
        generator.writeStartObject();
        generator.writeFieldName("key");
        generator.writeString(object.toString());
        generator.writeFieldName("status");
        generator.writeString(object.getDescription());
        generator.writeEndObject();
        generator.writeEndObject();
    }
}


我收到以下输出:

{
  "status" : {
    "key" : "ELSE",
    "status" : "desc"
  }
}

10-06 14:34