杰克逊没有通过泛型类型反序列化对象

时间:2019-06-23 16:47:59

标签: java spring spring-boot generics generic-programming

我正在尝试使用通用服务层和存储库层通过RestTemplate从后端服务中检索对象,我知道该后端服务将有效载荷序列化为正确类型Event

这是Event类:

@Data
@Entity
@Table(name = "event")
@NoArgsConstructor
@AllArgsConstructor
public class Event extends BaseEntity {

    @Column(name = "entity_id")
    private long entityId;

    @Column(name = "entity_type")
    private String entityType;

    @Column(name = "type")
    private String type;
}

ViewCommand<T>类:

@Getter
@Setter
@NoArgsConstructor
public class ViewCommand<T extends BaseEntity> {
    private List<T> results;
}

使用Spring Boot MVC通过Controller-> Service-> Repository服务于视图的前端服务,该存储库使用RestTemplate将请求发送到Backend服务。

这是控制器:

@Controller
public class EventController extends BaseController {

    private static final String PREFIX = "events";

    @Autowired
    private GenericService<Event> genericService;

    @GetMapping(PREFIX + "/{page}")
    public String events(final Model model) {
        ViewCommand<Event> command = genericService.list(PREFIX, Event.class.getName(), 0);
        model.addAttribute("command", command);
        return "events";
    }
}

通用服务类:

@Service
public class GenericService<T extends BaseEntity> {

    @Autowired
    private GenericRepository<T> genericRepository;

    public ViewCommand<T> list(String prefix, String className, int page) {
        return genericRepository.list(new ParameterizedTypeReference<>() {}, prefix, className, page);
    }
}

通用存储库类:

@Repository
public class GenericRepository<T extends BaseEntity> extends BaseRepository {
    private static final String LIST = "%s/list/%s/%s";

    @Value("${backend.uri}")
    private String backendUri;

    @Autowired
    private RestTemplate template;

    public ViewCommand<T> list(ParameterizedTypeReference<ViewCommand<T>> responseType, String prefix, String type, int page) {
        ViewCommand<T> body = template.exchange(backendUri + format(LIST, prefix, type, page), GET, getEntity(), responseType).getBody();
        return body;
    }
}

有人可以告诉我为什么results中的ViewCommand<T>列表反序列化为BaseEntity而不是Event的列表吗?

在使用T时Java没有选择类型ParameterizedTypeReference的地方,我在哪里出错?

0 个答案:

没有答案