2017-01-30 1 views
3

우리는 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 자신을 등록 할 수 있습니다

건배

답변

2

(즉, 어떤 차이가 있는지 우리는 봄에 RestTemplate과 함께 그것을 사용하고 있습니다).

0

는 별도로 출력 ObjectMapper를 구성 사용하여 출력을 쓰기 위해 그 사용

ObjectMapper outputMapper = new ObjectMapper(); 
outputMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); 

속성은 항상 뱀 경우에 기록되도록합니다.

PropertyNamingStrategy myStrategy = new PropertyNamingStrategy() { 
    @Override 
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) { 
     return PropertyNamingStrategy.SNAKE_CASE.nameForGetterMethod(config, method, defaultName); 
    } 

    @Override 
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) { 
     return PropertyNamingStrategy.LOWER_CAMEL_CASE.nameForSetterMethod(config, method, defaultName); 
    } 
}; 
: 당신은 단지 하나의 ObjectMapper 인스턴스를 사용해야 할 경우

또는 자신의 전달 ProptertyNamingStrategy를 만들