2017-02-20 35 views
3

我收到的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。如何使它在這種情況下工作?

+0

你可以圍繞Question pojo創建一個包裝類。由於包裝類將問題作爲數據成員,所以可以將json字符串轉換爲包裝類並檢索內部對象 –

回答

2

你的JSON定義地圖收藏的,所以你可以解析它的方式:

ObjectMapper mapper = new ObjectMapper(); 
Map<String, Question> questions = mapper.readValue(json, 
    new TypeReference<Map<String, Question>>(){}); 
Question question = questions.get("Question279"); 

new TypeReference<Map<String, Question>>(){}定義擴展TypeReference<Map<String, Question>>一個匿名類。其唯一目的是告訴Jackson它應該將JSON解析爲String-> Question對的映射。解析JSON之後,您需要從地圖中提取所需的問題。

4

試試這個可以是任何幫助

ObjectMapper mapper = new ObjectMapper(); 

String json = "{\"Question279\":{\"ID\":\"1\", \"Contents\":\"Some texts here\", \"User\":\"John\", \"Date\":\"2016-10-01\"}}"; 

mapper.readTree(json).fields().forEachRemaining(arg -> { 

    Question question = mapper.convertValue(arg.getValue(), Question.class); 

    System.out.println(question.getDate()); 
}); 

**由於存在從字符串沒有默認轉換到我LOCALDATE改變日期LOCALDATE到字符串日期Question.java

0

我建議讓您的ObjectMapper爲每種情況創建專門的ObjectReader

String questionKey = "Question279"; // Generate based on parameter used to obtain the json 
ObjectReader reader = mapper.reader().withRootName(questionKey).forType(Question.class); 
Question q = reader.readValue(json); 
... // Work with question instance