我一直在尝试升级 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);
}
}