Deserializing JSON with multiple types in one field

前端 未结 1 1376
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 04:41

I would like to deserialize JSON (with Jackson 1.9.11 and RestTemplate 1.0.1), in which one field may have more type meanings, for example:

    {\"responseId         


        
相关标签:
1条回答
  • 2020-12-10 05:22

    The only way to achieve that is to use a custom deserializer.

    Here is an example:

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
    testModule.addDeserializer(Response.class, new ResponseJsonDeserializer());
    mapper.registerModule(testModule);
    

    And here is how to write (how I would write it at least) the deserializer:

    class ResponseJsonDeserializer extends JsonDeserializer<Response>  {
      @Override
      public Responsedeserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Response response = new Response();
        if(jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            response.setError(jp.getText());
        } else {
           // Deserialize object
        }
        return response;
      }
    }
    
    class Response {
       private String error;
       private Object otherObject; // Use the real type of your object
    
       public boolean isError() {
          return error != null;
       }
    
       // Getters and setters
    
    }
    
    0 讨论(0)
提交回复
热议问题