Jackson/Gson 可以给我所有已知的可反序列化字段名称吗?

Can Jackson/Gson give me all known deserializable field names?

如果我有一个 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() {...}
}

或与Gson注解相同:

public class Item {

  @SerializedName("itemName")
  public String name;

  @SerializedName("number")
  private int quantity;

  ...
}

有没有办法使用 Jackson/Gson 获取它知道如何 反序列化 的所有字段名称(itemNamenumber在这种情况下)?

这是给杰克逊的:

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());
}

通话中:

System.out.println(getDeserializationProperties(Item.class));

输出:

[itemName, number]

对于 Gson,最接近的事情可能是序列化仅实例化的对象,然后将其转换为 JSON 树以提取 JSON 对象属性:

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

输出:

[itemName, number]