https://www.blockchain.com/api/blockchain_api
Blockchain.com Explorer | BTC | ETH | BCH
The easiest and most trusted transaction search engine and block explorer.
www.blockchain.com
위 홈페이지에서 특정 API를 호출하면 값이 아래처럼 넘어옵니다.
{
"addresses": [
{
"address": "xpub address",
"change_index": 1,
"account_index": 91,
"final_balance": 12693908,
"n_tx": 19,
"total_received": 12908908,
"total_sent": 215000
}
]
}
위처럼 넘어오는 값을 받기 위해서 도메인을 하나 생성합니다.
@Data
public class BtcAddressDomain {
private String address;
private int changeIndex;
private int accountIndex;
private BigInteger finalBalance;
private int nTx;
private BigDecimal totalReceived;
private BigDecimal totalSent;
}
이후 RestTemplate을 사용해서 해당 API를 호출한 결과값을 objectMapper.convertValue를 BtcAddressDomain에 넣어줍니다.
// responseEntity = restTemplate exchange 호출 결과값
BtcAddressDomain btcAddressDomain = objectMapper.convertValue(responseEntity.getBody(), BtcAddressDomain.class);
결과를 확인해보면 btcAddressDomain에는 address 필드에는 값이 제대로 들어가 있고, 나머지 필드에는 값이 null로 들어가 있습니다.
이유는 해당 API 서버가 응답값을 snakecase로 넘겨주는데 제가 생성한 도메인은 camelcase로 생성하여 매핑이 올바르게 되지 않았기 때문입니다.
이러한 상황처럼 snakecase로 값이 넘어왔을 때 camelcase로 변환시켜줘야 할 필요성이 있습니다.
총 3가지 방법이 있습니다. 사용 범위가 가장 큰 범위부터 낮은 범위까지 차례대로 알아보겠습니다.
1. ObjectMapper 자체에 기본 설정
restTemplate 결과값을 도메인으로 변환시킬 때 objectMapper를 활용하고 있습니다.
ObjectMapper 자체에 snakecase -> camelcase 변환이 가능하도록 기본 설정값을 지정하면 됩니다.
@Configuration
public class GlobalConfig {
@Bean(name = "objectMapper")
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// snakeCase -> camelCase
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
return objectMapper;
}
}
이렇게 기본값을 설정하면 모든 패키지 내에서 objectMapper로 convert할 때 snakecase -> camelcase가 적용됩니다.
2. @JsonNaming
1번 방법이 전역 범위세팅이라면 2번 방법은 @JsonNaming을 활용해서 클래스로 범위를 축소시킬 수 있습니다. 제가 가장 선호하는 방식입니다.
@Data
@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)
public class BtcAddressDomain {
private String address;
private int changeIndex;
private int accountIndex;
private BigInteger finalBalance;
private int nTx;
private BigDecimal totalReceived;
private BigDecimal totalSent;
}
위처럼 @JsonNaming을 사용하면 역직렬화 시 해당 클래스만 snakecase -> camelcase 변환이 적용됩니다.
3. @JsonProperty
snakecase를 camelcase로 변환하는 방법 중 가장 범위가 좁은 필드에 지정하는 방법입니다.
@Data
public class BtcAddressDomain {
private String address;
@JsonProperty("change_index");
private int changeIndex;
@JsonProperty("account_index");
private int accountIndex;
@JsonProperty("final_balance");
private BigInteger finalBalance;
@JsonProperty("n_tx");
private int nTx;
@JsonProperty("total_received");
private BigDecimal totalReceived;
@JsonProperty("total_sent");
private BigDecimal totalSent;
}
원하는 필드만 적용이 필요한 경우에 사용하면 됩니다.
이렇게 역직렬화 시 SnakeCase를 CamelCase로 변환하는 3가지 방법을 알아보았습니다.
개인적인 생각으로는 1번 전역으로 ObjectMapper 세팅을 지정하는 방식은 유연성이 가장 떨어지는 방법이라 사용하지 않는게 좋을 것 같습니다.
2번, 3번을 필요할 때마다 바꿔가면서 사용하면 괜찮을 것 같습니다.