如何解决JSON类型对象的Java反序列化不起作用
这是正在传递给我的数据。我无法控制此数据的结构:
{
"getParentCommunications":{
"ccList":[
{
"personId":12,"parentFirstNm":"johnny"
},{
"personId":14,"parentFirstNm":"Sue"
},{
"personId":19,"parentFirstNm":"Ashley"
}
]
}
}
我希望能够获取ccList数据并查看其中的信息。我试图将他的数据放入Java类中,以便可以根据需要进行操作。
使用杰克逊,我有这段代码
ClientResponse response = webResource.post(ClientResponse.class,input);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
GetParentCommunications gpc = mapper.readValue(response.getEntity(String.class),GetParentCommunications.class);
List<CcList> cclist = gpc.getCcList();
System.out.println( "size " + cclist.size()); //(produces a java.lang.NullPointerException)
最后,我认为我的两个课程将为我提供所需的数据。 GetParentCommunications
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonPropertyOrder({
"ccList"
})
public class GetParentCommunications implements Serializable
{
@JsonProperty("ccList")
private List<CcList> ccList = null;
@JsonIgnore
private Map<String,Object> additionalProperties = new HashMap<String,Object>();
private final static long serialVersionUID = 8422191816885827338L;
@JsonProperty("ccList")
public List<CcList> getCcList() {
return ccList;
}
@JsonProperty("ccList")
public void setCcList(List<CcList> ccList) {
this.ccList = ccList;
}
@JsonAnyGetter
public Map<String,Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name,Object value) {
this.additionalProperties.put(name,value);
}
}
和CcList
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonPropertyOrder({
"personId","parentFirstNm"
})
public class CcList {
@JsonProperty("personId")
private Integer personId;
@JsonProperty("parentFirstNm")
private String parentFirstNm;
@JsonIgnore
private Map<String,Object>();
@JsonProperty("personId")
public Integer getPersonId() {
return personId;
}
@JsonProperty("personId")
public void setPersonId(Integer personId) {
this.personId = personId;
}
@JsonProperty("parentFirstNm")
public String getParentFirstNm() {
return parentFirstNm;
}
@JsonProperty("parentFirstNm")
public void setParentFirstNm(String parentFirstNm) {
this.parentFirstNm = parentFirstNm;
}
@JsonAnyGetter
public Map<String,value);
}
}
解决方法
您需要反序列化为以GetParentCommunications类的对象为属性的类。该属性需要使用@JsonProperty(“ getParentCommunications”)进行标记。
另一方面,仅用@JsonProperty装饰的属性就足够了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。