代码之家  ›  专栏  ›  技术社区  ›  atlas_scoffed

来自JSON路径结果的泛型列表类型

  •  1
  • atlas_scoffed  · 技术社区  · 6 年前

    我想使用POJO序列化一些JSON,基于作为参数传递的泛型类。

    泛型类应该扩展一个抽象类,这样我就可以调用结果数据结构上的一些常用方法。

    到目前为止我已经知道了:

    private <T extends TypeInterface> List<DBObject> getDataUsingJsonPath(String path, Class<T> type) {
    
        TypeRef<List<T>> typeRef = new TypeRef<List<T>>() {};
    
        Configuration configuration = Configuration
            .builder()
            .mappingProvider(new JacksonMappingProvider())
            .jsonProvider(new JacksonJsonProvider())
            .build();
    
        List<T> items = JsonPath.using(configuration).parse(jsonString).read(path, typeRef);
    
        result = items.getAggregations();
    

    错误:

    无法构造TypeInterface的实例,问题:抽象类型 要么需要映射到具体类型,要么有自定义的反序列化程序, 或者用其他类型信息实例化

    3 回复  |  直到 6 年前
        1
  •  1
  •   Kiskae    6 年前

    编译器将编译 new TypeRef<List<T>>() {}; 作为参考 List<T extends TypeInterface> type .

    1. TypeToken<T> 就像你一样 TypeRef<T> .where(new TypeParameter<T>() {}, type) 将类型变量细化为最终类型。
    2. 围绕新的typetoken创建一个包装器,该标记为JsonPath提供了经过优化的类型:

    包装:

    class TokenRef<T> extends TypeRef<T> {
        private final TypeToken<T> token;
    
        public TokenRef(TypeToken<T> token) {
            super();
            this.token = token;
        }
    
        @Override
        public Type getType() {
            return this.token.getType();
        }
    }
    
        2
  •  1
  •   user10527814 user10527814    6 年前

    private <T extends TypeInterface> List<DBObject> getDataUsingJsonPath(String path, Class<T> type) {
    
        Configuration configuration = Configuration
            .builder()
            .mappingProvider(new JacksonMappingProvider())
            .jsonProvider(new JacksonJsonProvider())
            .build();
    
    List<T> items = JsonPath.using(configuration).parse(jsonString).read(path, (Class<List<T>>) new ArrayList<T>().getClass());
    

    我们的想法是摆脱 TypeRef<List<T>>

        3
  •  0
  •   atlas_scoffed    6 年前

    这里有一些很好的答案,但是在睡眠之后,我选择将TypeRef移动为实际参数。

    private <T extends TypeInterface> List<DBObject> getDataUsingJsonPath(String path, TypeRef<List<T>> type) {
    

    List<T> items = JsonPath.using(configuration).parse(responseString).read(path, type);
    
    for(T item : items) {
    // do generic TypeInterface stuff here
    

    我不知道这是否是最好的,最正确的,“通用”方法,但到目前为止还不错,在阅读我认为的代码时基本上是有意义的。