我们在后端使用了一个API,该API输出camelCased属性,将其映射到POJO,应用一些业务逻辑,然后将其与我们的API一起输出到某些应用程序。我们要输出的格式是snake_case属性。
该测试描述了我们想要做什么:
@Test
public void mappingTest() throws IOException {
String input = "{ \"merchantId\": 23, \"contactName\": \"foobar\" }";
ObjectMapper mapper = new ObjectMapper();
Merchant merch = mapper.readValue(input, Merchant.class);
String output = mapper.writeValueAsString(merch);
String expectedOutput = "{ merchant_id: 23, contact_name: 'foobar' }";
assertEquals("", expectedOutput, output);
}
目前,模型类如下所示:
@JsonInclude(Include.NON_NULL)
public class Merchant {
private String merchantId;
private String contactName;
public Merchant() {
}
public Merchant(final String merchantId, final String contactName) {
this.merchantId = merchantId;
this.contactName = contactName;
}
@JsonProperty("contact_name")
public String getContactName() {
return contactName;
}
@JsonProperty("contactName")
public void setContactName(final String contactName) {
this.contactName = contactName;
}
@JsonProperty("merchant_id")
public String getMerchantId() {
return merchantId;
}
@JsonProperty("merchantId")
public void setMerchantId(final String merchantId) {
this.merchantId = merchantId;
}
}
它可以工作,但我认为它不是很优雅,因为我们的输入始终是驼峰形,而输出始终是蛇形。有没有一种方法可以将杰克逊的JSON序列化全局设置为snakecase,反序列化为camelcase?(如果有什么区别,我们将它与Spring中的RestTemplate一起使用)
干杯
您可以实现并注册自己的方法,分别PropertyNamingStrategy
为public String nameForGetterMethod(...)
和public String nameForSetterMethod(...)
方法定义不同的逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句