簡體   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