Jackson deserialization of type with different objects

前端 未结 4 1546
清酒与你
清酒与你 2020-12-06 02:21

I have a result from a web service that returns either a boolean value or a singleton map, e.g.

Boolean result:

{
    id: 24428,
    rated: false
}
<         


        
4条回答
  •  暖寄归人
    2020-12-06 03:01

    No no no. You do NOT have to write a custom deserializer. Just use "untyped" mapping first:

    public class Response {
      public long id;
      public Object rated;
    }
    // OR
    public class Response {
      public long id;
      public JsonNode rated;
    }
    Response r = mapper.readValue(source, Response.class);
    

    which gives value of Boolean or java.util.Map for "rated" (with first approach); or a JsonNode in second case.

    From that, you can either access data as is, or, perhaps more interestingly, convert to actual value:

    if (r.rated instanced Boolean) {
        // handle that
    } else {
        ActualRated actual = mapper.convertValue(r.rated, ActualRated.class);
    }
    // or, if you used JsonNode, use "mapper.treeToValue(ActualRated.class)
    

    There are other kinds of approaches too -- using creator "ActualRated(boolean)", to let instance constructed either from POJO, or from scalar. But I think above should work.

提交回复
热议问题