If I have a POJO:
public class Item {
@JsonProperty("itemName")
public String name;
private int quantity;
@JsonGetter("quantity") //call it "quantity" when serializing
public int getQuantity() {...}
@JsonSetter("number") //call it "number" when deserializing
public void setQuantity() {...}
}
or the same with Gson annotations:
public class Item {
@SerializedName("itemName")
public String name;
@SerializedName("number")
private int quantity;
...
}
Is there a way to use Jackson/Gson to get all field names that it would know how to deserialize (itemName
and number
in this case)?
This is for Jackson:
public static List<String> getDeserializationProperties(Class<?> beanType)
{
ObjectMapper mapper = new ObjectMapper();
JavaType type = mapper.getTypeFactory().constructType(beanType);
BeanDescription desc = mapper.getSerializationConfig().introspect(type);
return desc.findProperties().stream()
.filter(def -> def.couldDeserialize())
.map(def -> def.getName())
.collect(Collectors.toList());
}
Calling:
System.out.println(getDeserializationProperties(Item.class));
Output:
[itemName, number]