我使用spring restTemplate并将 json 响应转换为 pojo。但是得到一个JsonMappingException
POJO
@Root
public class Account {
@Element
private int id;
@Element
private int customerId;
@Element
private AccountType type;
@Element
private BigDecimal balance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public AccountType getType() {
return type;
}
public int getIntType() {
return type.ordinal();
}
public void setType(AccountType type) {
this.type = type;
}
public void setType(int type) {
this.type = AccountType.values()[type];
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public BigDecimal getAvailableBalance() {
return balance.signum() < 0 ? new BigDecimal(0) : balance;
}
public void credit(BigDecimal amount) {
balance = balance.add(amount);
}
public void debit(BigDecimal amount) {
balance = balance.subtract(amount);
}
public static enum AccountType {
CHECKING(false), SAVINGS(false), LOAN(true);
private boolean internal;
private AccountType(boolean internal) {
this.internal = internal;
}
public boolean isInternal() {
return internal;
}
}
}
休息客户端
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
supportedMediaTypes.add(mediaType);
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
jacksonConverter.setSupportedMediaTypes(supportedMediaTypes);
messageConverters.add(jacksonConverter);
restTemplate.setMessageConverters(messageConverters);
Account [] accounts = restTemplate.getForObject(url, new Account[0].getClass());`
例外
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Conflicting setter definitions for property "type": com.entity.Account#setType(1 params) vs com.entity.Account#setType(1 params); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property "type": com.entity.Account#setType(1 params) vs com.entity.Account#setType(1 params)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)`