使用Jackson2.4解析屬性首字母為大寫的JSON串
阿新 • • 發佈:2019-01-28
今天在做Docker的管理工具時,遇到一個解析JSON串的問題,由於Docker返回的JSON屬性的首字母都為大寫,如下
[ { "Created": 1422514187, "Id": "2ef051877a7aeb4041c343b2f941a7628c5787fc1d4dbcdd3cf4af71cd28cab4", "ParentId": "372c34633691fea23decca8f2c400877ad33b6ecddcd899a20b9cb9734f0265d", "RepoTags": [ "zhangjy/starsms:v2" ], "Size": 0, "VirtualSize": 703334375 } ]
物件定義如下
這樣導致使用Jackson解析出來的物件的屬性均為空,即使把Image物件的屬性首字母均改為大寫也不行,經過跟蹤原始碼發現,是由於其根據getters方法解析的屬性,屬性字母都變為了小寫package com.dms.domain; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class Image implements Serializable { private static final long serialVersionUID = -895599442916010326L; private Long created; private String id; private String parentId; private List<String> repoTags; private Long size; private Long virtualSize; private String host; //getters and setters }
解決方法如下:
一是,將Image物件的屬性首字母都改為大寫,且是public型別,但這種命名感覺很彆扭
二是,使用Jackson的JsonProperty註解
package com.dms.domain; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class Image implements Serializable { private static final long serialVersionUID = -895599442916010326L; @JsonProperty(value = "Created") private Long created; @JsonProperty(value = "Id") private String id; @JsonProperty(value = "ParentId") private String parentId; @JsonProperty(value = "RepoTags") private List<String> repoTags; @JsonProperty(value = "Size") private Long size; @JsonProperty(value = "VirtualSize") private Long virtualSize; private String host; public Long getCreated() { return created; } public void setCreated(Long created) { this.created = created; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public List<String> getRepoTags() { return repoTags; } public void setRepoTags(List<String> repoTags) { this.repoTags = repoTags; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public Long getVirtualSize() { return virtualSize; } public void setVirtualSize(Long virtualSize) { this.virtualSize = virtualSize; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } }