繁体   English   中英

有没有办法将列表 Object 转换为通用 function 中的确切列表 Class?

[英]Is there a way to cast List Object into exact List Class in an generic function?

I am coding in an Spring Boot Project and there was a lot of API with diffrent Request Param so I'm trying to write a generic function with mapper an request param into a list object, then cast it into a class like the code below

    public static <D> List<D> convertStringListToObject(String string) {
        if (string == null) return null;
        try {
            return objectMapper.readValue(string, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

但结果是它只能返回 Object 的列表,而不是我预期的 D class 的列表。 有谁知道如何编写这个 function?

编辑:这是我调用它的方式:

filterBlockRequestDto.setPopularFiltersList(ApiUtil.convertStringListToObject(filterBlockRequestDto.getPopularFilters()));

FilterBlockRequestDto class

package com.levitate.projectbe.dto.filter;

import com.levitate.projectbe.dto.common.PopularFiltersDto;
import com.levitate.projectbe.dto.common.TotalBudgetDto;
import lombok.*;

import java.util.List;

@Getter
@Setter
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class FilterBlockRequestDto {
    Integer locationId;
    Integer projectId;
    String totalBudget;
    List<TotalBudgetDto> totalBudgetList;
    // The string was pass in Request param
    String popularFilters;
    List<PopularFiltersDto> popularFiltersList;
    Integer viewRating;
    Integer numberOfBed;
}

一种方法是接受类型引用作为参数,以便调用者可以提供目标 class 并且由于TypeReference是子类,因此在运行时将提供泛型类型信息。

    public static <D> List<D> convertStringListToObject(String string, TypeReference<List<D>> typeReference) {
        if (string == null) return null;
        try {
            return objectMapper.readValue(string, typeReference);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

您还必须将要反序列化字符串的类型传递给..

我的方法是这样的:

public static <T> T convertStringListToObject(String string, Class<T> clazz) {
    if (string == null) {
        return null;
    }
    try {
       return objectMapper.readValue(string, clazz);
    } catch (JsonProcessingException e) {
       e.printStackTrace();
    }
    return null;
}

然后按如下方式使用此方法:

List<Model> models = 
    Arrays.asList(Mapper.convertStringListToObject(stringList, Model[].class));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM