相关疑难解决方法(0)

杰克逊databind enum不区分大小写

如何反序列化包含不区分大小写的枚举值的JSON字符串?(使用Jackson Databind)

JSON字符串:

[{"url": "foo", "type": "json"}]
Run Code Online (Sandbox Code Playgroud)

和我的Java POJO:

public static class Endpoint {

    public enum DataType {
        JSON, HTML
    }

    public String url;
    public DataType type;

    public Endpoint() {

    }

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,反序列化JSON "type":"json"将失败,因为它"type":"JSON"可以工作.但我想"json"以命名惯例为理由.

序列化POJO也会导致大写 "type":"JSON"

我想过使用@JsonCreator和@JsonGetter:

    @JsonCreator
    private Endpoint(@JsonProperty("name") String url, @JsonProperty("type") String type) {
        this.url = url;
        this.type = DataType.valueOf(type.toUpperCase());
    }

    //....
    @JsonGetter
    private String getType() {
        return type.name().toLowerCase();
    }
Run Code Online (Sandbox Code Playgroud)

它奏效了.但我想知道是否有更好的解决方案,因为这看起来像是对我的黑客攻击.

我也可以编写一个自定义反序列化器,但是我有很多不同的POJO使用枚举,而且很难维护.

任何人都可以建议一个更好的方法来使用适当的命名约定序列化和反序列化枚举?

我不希望我在java中的枚举是小写的!

这是我使用的一些测试代码:

    String data = "[{\"url\":\"foo\", \"type\":\"json\"}]";
    Endpoint[] …
Run Code Online (Sandbox Code Playgroud)

java enums serialization json jackson

80
推荐指数
8
解决办法
5万
查看次数

WebMvcConfigurationSupport和WebMvcConfigurerAdapter之间的区别

我想添加资源处理程序.在他们使用的论坛中WebMvcConfigurationSupport:http://forum.springsource.org/showthread.php?116068-How-to-configure-lt-mvc-resources-gt-mapping-to-take-precedence-over-RequestMapping&p=384066# post384066

和文档说WebMvcConfigurerAdapter:http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/config/annotation/EnableWebMvc.html

有什么区别,使用哪一个?两者都有addResourceHandlers我需要的方法.

这是我目前的课程:

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    public @Override void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
    }

    public @Bean TilesViewResolver tilesViewResolver() {
        return new TilesViewResolver();
    }

    public @Bean TilesConfigurer tilesConfigurer() {
        TilesConfigurer ret = new TilesConfigurer();
        ret.setDefinitions(new String[] { "classpath:tiles.xml" });
        return ret;
    }
}
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc

30
推荐指数
3
解决办法
3万
查看次数

标签 统计

enums ×1

jackson ×1

java ×1

json ×1

serialization ×1

spring ×1

spring-mvc ×1