2017-02-20 30 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