Rotem
Rotem

Reputation: 11

Find the field type using Jackson JSON

I am trying to do reflection using Jackson. More specifically, I would like to retrieve the type,name, and value of every field in a particular class. I am able to get the name and the value of a field using ObjectMapper, but I can't seem to find a method to retrieve the type. My code is listed below:

ObjectMapper mapper = new ObjectMapper();

University uni = new University();
String uniJSON = mapper.writeValueAsString(uni);
System.out.println(uniJSON);

Output:

{"name":null,"ae":{"annotationExampleNumber":0},"noOfDepartments":0,"departments":null}

Upvotes: 1

Views: 4088

Answers (2)

cirovladimir
cirovladimir

Reputation: 613

You could use generateJsonSchema method as follows

try{
    ObjectMapper json=new ObjectMapper();
    json.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    System.out.println(json.generateJsonSchema(University.class).toString());
}catch(Exception e){
    throw new RuntimeException(e);
}

This produces a json schema which you could read to get field data types. Be aware that this method generates a JSON schema, hence, it only uses JSON allowed data types (string, number, boolean, object, array and null).

If you want the Java Types, you should use reflection. Be warned, there are complex issues like circular references, arrays, etc. If you know the name of the property you're trying to identify its type, you could do something similar to this. This works with nested properties if you pass on a parameter like "principal.name"

private Class<?> getPropertyType(Class<?> clazz,String property){
try{
    LinkedList<String> properties=new LinkedList<String>();
    properties.addAll(Arrays.asList(property.split("\\.")));
    Field field = null;
    while(!properties.isEmpty()){
        field = clazz.getDeclaredField(properties.removeFirst());
        clazz=field.getType();
    }
    return field.getType();
}catch(Exception e){
    throw new RuntimeException(e);
}
}

Upvotes: 1

Istvan Devai
Istvan Devai

Reputation: 4022

Annotate your domain classes with Jackson annotations to do that:

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="type")
public class University {

See this for more info: http://www.cowtowncoder.com/blog/archives/2010/03/entry_372.html

Upvotes: 0

Related Questions