使用jackson时,跳过JSON中的第一级

Sea*_*ene 5 java json jackson

我收到的JSON对象是这样的.

{  
   "Question279":{  
      "ID":"1",
      "Contents":"Some texts here",
      "User":"John",
      "Date":"2016-10-01"
}
Run Code Online (Sandbox Code Playgroud)

我需要将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...
}
Run Code Online (Sandbox Code Playgroud)

另请注意,上述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);
Run Code Online (Sandbox Code Playgroud)

但它没有用,当然,我上了一堂Questionnull.在这种情况下如何使它工作?

Ken*_*ter 2

您的 JSON 定义了集合映射,因此您可以这样解析它:

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

定义new TypeReference<Map<String, Question>>(){}了一个扩展的匿名类TypeReference<Map<String, Question>>。它的唯一目的是告诉 Jackson 它应该将 JSON 解析为字符串->问题对的映射。解析 JSON 后,您需要从地图中提取所需的问题。