Java Jackson/Gson能给我所有已知的可反序列化字段名吗?
如果我有一个POJO:Java Jackson/Gson能给我所有已知的可反序列化字段名吗?,java,json,jackson,gson,jackson2,Java,Json,Jackson,Gson,Jackson2,如果我有一个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" w
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
)这是针对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());
}
输出:
[itemName, number]
对于Gson,最接近的事情可能是序列化一个仅实例化的对象,然后将其转换为JSON树,以便提取JSON对象属性:
final类项目{
@SerializedName(“itemName”)
字符串名;
@序列化名称(“编号”)
整数;
}
final Gson Gson=new GsonBuilder()
.serializeNulls()//这是必需的:默认情况下Gson排除null值,否则仅排除基元值
.create();
最终列表名称=gson.toJsonTree(新项())
.getAsJsonObject()
.entrySet()
.stream()
.map(条目::getKey)
.collect(toList());
System.out.println(名称);
输出:
[项目名称、编号]
你能详细说明你的问题吗。我无法理解你的要求好的,我删除了副本。对不起我的错误。再次感谢你的帮助!我去问问梅塔。
[itemName, number]