我无法获取发送到pojo的json字符串。
com.fasterxml.jackson.databind.JsonMappingException:无法从START_ARRAY标记中反序列化com.sg.info.Account的实例 在[来源:java.io.StringReader@1f6dcfe2; line:1,column:1]
这是json
[{"accno":9210255,"type":"Stock- and mutual funds account","default":true,"alias":"Karlsson Joachim"}]
解析
public void getAccounts()
{
ObjectMapper mapper = new ObjectMapper();
String resp = Login.getBaseResource().path("accounts").request(Login.getResponsetype()).get(String.class);
try {
account = mapper.readValue(resp, Account.class);
POJO
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Account {
public Account() {
}
private long accno;
private String type;
@JsonProperty("default")
private String isDefault;
private String alias;
public long getAccno() {
return accno;
}
public void setAccno(long accno) {
this.accno = accno;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
@Override
public String toString() {
return "Account [accno=" + accno + ", type=" + type + ", alias="
+ alias + "]";
}
public String isDefault() {
return isDefault;
}
@JsonProperty("default")
public void setDefault(String isDefault) {
this.isDefault = isDefault;
}
}
答案 0 :(得分:1)
您遇到的问题是您拥有的JSON是一个数组,并且可以拥有多个帐户。如果您将解析代码更改为类似的内容,它将起作用:
ObjectMapper mapper = new ObjectMapper();
String str = "[{\"accno\":9210255,\"type\":\"Stock- and mutual funds account\",\"default\":true,\"alias\":\"Karlsson Joachim\"}]";
JavaType accountListType = mapper.getTypeFactory().constructArrayType(Account.class);
Account[] accounts = SharedJsonSerializer.objectMapper().readValue(str, accountListType);
当然最好使用集合类型,你可以使用mapper.getTypeFactory()构建你想要的任何类型