如何使用jackson将json数据下面的反序列化到集合列表中?

时间:2017-06-15 10:59:05

标签: json jackson

{
    "TOTALRECORDCOUNT": 588,
    "RECORDCOUNT": 588,
    "HASMORE": false,
    "RECORDSET": {
        "COLUMNS": [
            "PARTNERSEGMENTID",
            "ORGANIZATIONID",
            "ORGANIZATIONNAME",
            "PROGRAMTRACK",
            "PARTNERLEVEL"
        ],
        "DATA": [
            [
                "Partner_Segment_GES",
                1,
                "Relayware",
                "ProgramTrack_SolutionPartner",
                "AuthorizedLevel"
            ],
            [
                "Partner_Segment_GES",
                2,
                "Tata Communications",
                "ProgramTrack_SolutionPartner",
                null
            ],

1 个答案:

答案 0 :(得分:0)

您可以使用jackson @JsonRootName注释,因为您发布的json只有一个顶级键。如果还有更多,你可以创建一个pojo,其中recordSet是一个字段。

  1. 当json只有recordSet作为顶级键时的情况: 这是代码:记录集的Pojo

    @JsonRootName("RECORDSET")
    class RecordSet{
    
       @JsonProperty("DATA")
       List<List<String>> data;
    
       @JsonProperty("COLUMNS")
       List<String> columns;
    
       //getter and setter
    }
    
  2. 将json反序列化为RecordSet对象的代码

    String jsonString="{ \"RECORDSET\": { \"COLUMNS\": [ \"MEMBERSHIPLEVEL\", \"PARTNERSEGMENTID\", \"ORGANIZATIONID\", \"ORGANIZATIONNAME\", \"PROGRAMTRACK\", \"CREATED\" ], \"DATA\": [ [ \"ProgramLevel_Premier\", \"Partner_Segment_GES\", 2, \"Tata Communications\", \"ProgramTrack_SolutionPartner\", \"2008-06-10T20:03:07Z\" ] ] } }";
    
            ObjectMapper mapper=new ObjectMapper();
            mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    
            RecordSet recordSet = mapper.readValue(jsonString, RecordSet.class);
    
           //The below two statements can be replaced with the logic that you want to operate on deserialized object
            System.out.println(recordSet.getColumns());
            System.out.println(recordSet.getData());
    
    1. 当totalRecordSetCount和其他字段是顶级json的一部分时的情况:

      class Response{
      
         @JsonProperty("HASMORE")
         private boolean hasMore;
      
         @JsonProperty("RECORDCOUNT")
         private int recordCount;
      
         @JsonProperty("TOTALRECORDCOUNT")
         private int totalRecordCount;
      
         @JsonProperty("RECORDSET")
         RecordSet recordSet;
      
        //getter and setter
      }
      
    2. 从案例#1

      获取RecordSet pojo

      反序列化代码:

        ObjectMapper mapper=new ObjectMapper();
                  Response response = mapper.readValue(jsonString, Response.class);
      
                  RecordSet recordSet = response.getRecordSet();
      
      
       //The below two statements can be replaced with the 
       //logic that you want to operate on deserialized object
      
                  System.out.println(recordSet.getColumns());
                  System.out.println(recordSet.getData());