Search code examples
javajsonspringresttemplate

Complex Json Mapping in Spring with RestTemplate


I am trying to map a jsonResponse with my Java entity class. The json response looks as follow

   "classResults":{
      "classSuggestion":[
          "classA",
          {
            "section":"section c"
          }
      ]
    }
    

My Java Class for mapping might looks something like this. I will have an object of ClassSuggestion in order to map classSuggestion object. However how would the classSuggestion be to hold the json data as above ?

public class ClassResults {

   ClassSuggestion classSuggestion

}

How would my ClassSuggestion be ?

public class ClassSuggestion {

   String classes
   String section
}

How do I map this to a Java Class or data type ?


Solution

  • I solved this by writing a custom deserializer:

    class ClassSuggestionDeserializer extends StdDeserializer<Employee> {
    
       @Override
       public Map<String, String> deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
          ObjectCodec codec = jp.getCodec();
          TreeNode node = codec.readTree(jp);
          JsonNode classResults = node.get("classResults");
          // and finally iterating through the classResults to get string values
       }
    }
    

    Meanwhile on the data class,used JsonDeserialize using the custom deserializer.

    @JsonDeserialize(using=ClassSuggestionDeserializer.class)
    public class ClassSuggestion {
    
       Map<String, String> classResults;
    
     }