1

I'm trying to build a JPA CriteriaQuery from a client-provided JSON filter; that is, to query this Person POJO:

@Entity
public class Person {

    @Id
    public Long id;

    public String name;

    public Date dateOfBirth;

}

a client would provide a JSON like this

{
    "$or": [
        { "name":        { "$beginsWith": "Jo" } },
        { "dateOfBirth": { "$lessThan":   "1983-01-01T00:00:00Z" } }
    ]       
}

When parsing this filter, I need to obtain the right Java type from the provided JSON values, e.g. a Date for dateOfBirth. Given that I can easily reach the JsonNode for "1983-01-01T00:00:00Z" and that Jackson's ObjectMapper knows somewhere what type to deserialize for the dateOfBirth field of Person.class, how can I get it? Ideally it would be something in the lines of:

// jsonNode is the JsonNode for "1983-01-01T00:00:00Z"

ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerFor(Person.class);
Date date = (Date) reader.asField("dateOfBirth").readValue(jsonNode);

That asField() method would do the magic to return a reader which will read a JSON string as Java Date (or more generally the type that the ObjectMapper would resolve applying [de]serializers annotated for that field).

Note: I'm not asking how to parse dates with Jackson, but how to read a value and get the object Jackson would deserialize normally, but for a nested field.

Giovanni Lovato
  • 2,183
  • 2
  • 29
  • 53
  • See http://www.baeldung.com/jackson-serialize-dates - Use @JsonFormat to format Date – bodo Jan 22 '16 at 09:46
  • @bodo `Date` is just an example type, it could be anything. I'll try to make the answer more clear. – Giovanni Lovato Jan 22 '16 at 09:48
  • This is an example how to convert json string which contains date format as String to Date. Is that what you have been searching for, isn't it? – bodo Jan 22 '16 at 09:53
  • Ok I see, this is an example with mixin (this is serializing to json, but it doesn't matter) http://stackoverflow.com/questions/21751615/how-to-map-the-mixins-for-the-nested-json-response May be more accurate for your problem – bodo Jan 22 '16 at 09:59
  • @bodo Nope, I don't know to which type I need to deserialize the value, it could be anything. I need to tell `ObjectMapper` "deserialize this `JsonNode` as you would do if the node was for field `foo` of `MyBean.class`; since the `ObjectMapper` knows well, I'm trying to get this information. – Giovanni Lovato Jan 22 '16 at 10:06
  • Am I understand right, the `foo` should be any nested type? – bodo Jan 22 '16 at 10:10
  • @bodo Yes, `foo` could be any nested type. – Giovanni Lovato Jan 22 '16 at 10:32
  • I don't think this is achievable with Jackson ObjectMapper, I suppose that CriteriaQuery can contain a bunch of leafs with conditions, so I think you need to use [JacksonStreamingApi](http://wiki.fasterxml.com/JacksonStreamingApi) or write bunch of custom deserializers. – bodo Jan 22 '16 at 12:06

0 Answers0