如果我有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获取所有字段名称,知道如何反序列化(在这种情况下itemName
和number
)?
答案 0 :(得分:2)
这是给杰克逊的:
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]
答案 1 :(得分:2)
对于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]