【问题标题】:Can Jackson/Gson give me all known deserializable field names?Jackson/Gson 可以给我所有已知的可反序列化字段名称吗?
【发布时间】:2017-02-26 23:32:01
【问题描述】:

如果我有 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)?

【问题讨论】:

  • 你能详细说明你的问题吗?我无法按照您的要求进行操作

标签: java json jackson gson jackson2


【解决方案1】:

这是给杰克逊的:

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]

【讨论】:

    【解决方案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);
    

    输出:

    [项目名称,编号]

    【讨论】:

    • 好的,我删除了副本。对不起我的错误。再次感谢您的帮助!我会在 Meta 上问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多