在使用Jackson进行反序列化时,如何放松命名策略?

Mri*_*lla 9 java json jackson fasterxml jackson-modules

我一直在尝试升级JSON模块以使用Jackson的FasterXML(2.6.3)版本而不是旧的Codehaus模块.在升级过程中,我注意到使用FasterXML而不是Codehaus时命名策略有所不同.

Codehaus在命名策略方面更灵活.下面的测试突出了我用FasterXML面临的问题.我如何配置ObjectMapper它遵循Codehaus相同的策略?

我不能改变JSONProperty注释,因为有数百个注释.我希望升级在命名策略方面向后兼容.

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
/*import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.PropertyNamingStrategy;*/
import org.junit.Assert;
import org.junit.Test;

public class JSONTest extends Assert {

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class Product {

        @JsonProperty(value = "variationId")
        private String variantId;

        @JsonProperty(value = "price_text")
        private String priceText;

        @JsonProperty(value = "listPrice")
        public String listPrice;

        @JsonProperty(value = "PRODUCT_NAME")
        public String name;

        @JsonProperty(value = "Product_Desc")
        public String description;
    }

    private static final String VALID_PRODUCT_JSON =
            "{ \"list_price\": 289," +
             " \"price_text\": \"269.00\"," +
             " \"variation_id\": \"EUR\"," +
             " \"product_name\": \"Product\"," +
             " \"product_desc\": \"Test\"" +
            "}";

    @Test
    public void testDeserialization() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

        Product product = mapper.readValue(VALID_PRODUCT_JSON, Product.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(product));
        assertNotNull(product.listPrice);
        assertNotNull(product.variantId);
        assertNotNull(product.priceText);
        assertNotNull(product.name);
        assertNotNull(product.description);
    }
}
Run Code Online (Sandbox Code Playgroud)

Yos*_*ner 9

@JsonProperty从版本2.4.0开始,覆盖PropertyNamingStrategy fastxml中的任何内容.但是,尚未发布的2.7.0版本将提供一项功能,允许您选择重新使用旧行为.还有一个未实现的建议是在每个注释级别切换这个,但这对你没有帮助.

看起来Codehaus 在映射时确实应用了值的PropertyNamingStrategy顶部@JsonProperty,尽管我找不到任何明确的文档.这似乎也是2.4.0之前的fastxml中的行为.是另一个注意到行为相同差异的例子.