我收到的JSON對象是這樣的。使用jackson跳過JSON的第一級
{
"Question279":{
"ID":"1",
"Contents":"Some texts here",
"User":"John",
"Date":"2016-10-01"
}
我需要將JSON映射到以下java bean。
public class Question {
@JsonProperty("ID")
private String id;
@JsonProperty("Contents")
private String contents;
@JsonProperty("User")
private String user;
@JsonProperty("Date")
private LocalDate date;
//some getters and setters are skipped...
}
還要注意的是在上面的JSON對象Question279
第一水平不總是相同的,這取決於提供給獲得JSON參數用戶。我無法改變這種情況。
目前我正在使用這樣的東西。
ObjectMapper mapper = new ObjectMapper();
String json = "{'Question279':{'ID':'1', 'Contents':'Some texts here', 'User':'John', 'Date':'2016-10-01'}"
Question question = mapper.readValue(json, Question.class);
但它不工作,當然,我得到了Question
類充滿null
。如何使它在這種情況下工作?
你可以圍繞Question pojo創建一個包裝類。由於包裝類將問題作爲數據成員,所以可以將json字符串轉換爲包裝類並檢索內部對象 –