우리는 camelCased 속성을 출력하는 백엔드 API를 사용하고이를 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;
}
}
그것은 작동하지만 나는 우리의 입력이기 때문에 매우 우아하지 생각
이 테스트는 우리가 수행 할 작업을 설명합니다 항상 camelcase이고 출력은 항상 snakecase입니다. 잭슨에 대해 JSON 직렬화를 snakecase 및 deserialization에 camelcase로 설정하는 방법이 있습니까? 당신은 구현하고 각각 public String nameForGetterMethod(...)
및 public String nameForSetterMethod(...)
방법에 대해 서로 다른 논리를 정의 할 경우 PropertyNamingStrategy
자신을 등록 할 수 있습니다
건배