2

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)?

kaqqao
  • 12,984
  • 10
  • 64
  • 118

2 Answers2

2

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]
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
2

For Gson, the closest thing could be serializing an instantiated-only object and then converting it to a JSON tree in order to extract the JSON object properties:

final class Item {

    @SerializedName("itemName")
    String name;

    @SerializedName("number")
    int quantity;

}
final Gson gson = new GsonBuilder()
        .serializeNulls() // This is necessary: Gson excludes null values by default, otherwise primitive values only
        .create();
final List<String> names = gson.toJsonTree(new Item())
        .getAsJsonObject()
        .entrySet()
        .stream()
        .map(Entry::getKey)
        .collect(toList());
System.out.println(names);

The output:

[itemName, number]

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
  • Ok, I removed the duplicate. Sorry for my error. And thanks again for the help! I'll ask on Meta. – kaqqao Feb 27 '17 at 10:12