当前位置: 首页 > 知识库问答 >
问题:

如何修复类java.util.LinkedHashMap无法强制转换为类java.lang.String错误

段干玺
2023-03-14

所以,我试图建立一个报告。某些特定类型的用户的详细信息需要写在excel文件中。在到达endpoint时,它返回500,并使用以下StackTrace。

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class java.lang.String (java.util.LinkedHashMap and java.lang.String are in module java.base of loader 'bootstrap')
        at com.clever.bas.util.Helpers.lambda$writeToExcel$0(Helpers.java:73)
        at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:721)
        at com.clever.bas.util.Helpers.lambda$writeToExcel$1(Helpers.java:64)
     
public static InputStream writeToExcel(Stream<UserProfile> data) throws Exception {

//        final Map<String, Transaction> transaction = data.collect(Collectors.toMap(Transaction::getId, Function.identity()));

//        System.out.println(transaction + " +++++>>>>>>");


        //Blank workbook
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {

            //Create a blank sheet
            XSSFSheet sheet = workbook.createSheet("transaction report");


            AtomicInteger rowNum = new AtomicInteger(1);

            AtomicBoolean isHeaderSet = new AtomicBoolean(false);
            data.forEach(userProfile -> {
                if (!isHeaderSet.get()){
                    createHeader(userProfile, sheet);
                    isHeaderSet.set(true);
                }
                XSSFRow row = sheet.createRow(rowNum.getAndIncrement());

                ObjectMapper mapObject = new ObjectMapper();
                Map<String, Object> mapObj = mapObject.convertValue(userProfile, Map.class);


                AtomicInteger cellNum = new AtomicInteger();
                mapObj.forEach((key, value) -> {
                    XSSFCell cell = row.createCell(cellNum.getAndIncrement());
                    cell.setCellValue(key);
                    if (value instanceof Integer)
                        cell.setCellValue((Integer) value);
                    else if (value instanceof BigDecimal)
                        cell.setCellValue(((BigDecimal) value).doubleValue());
                    else if (value instanceof Long)
                        cell.setCellValue((Long) value);
                    else cell.setCellValue((String) value);

                });
            });
public class UserProfile {


    @Id
    @ObjectId
    private String id;

    @JsonFormat(pattern="yyyy-MM-dd'T'HH:mm:ssZ")
    private final Date createdAt = new Date(System.currentTimeMillis());

    @JsonFormat(pattern="yyyy-MM-dd'T'HH:mm:ssZ")
    private final Date updatedAt = new Date(System.currentTimeMillis());


    private String agentId;

    @NotBlank
    private String firstName;

    @NotBlank
    private String lastName;

    @NotBlank
    @Email(message="Invalid email Address")
    private String email;

    @NotBlank
    @Size(min=11, max=14)
    private String phoneNumber;

    private String businessName;

    @Size(min=11, max=11)
    private String bvn;

    @Size(min=11, max=11)
    private String nin;

    @URL
    private String profilePicture;

    @URL
    private String utilityBill;

    @URL
    private String identityCard;

    private RoleGroup roleGroup;

    @Embedded
    private List<Role> roles;

    @ObjectId
    @JsonIgnore
    private List<String> roleIds;

    private String userType; // STAFF, AGENT, AGGREGATOR, PROSPECT

    public Types.Gender gender;

    private String referralCode;

    private String referral;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date dateOfBirth;

    private Types.VerificationStatus verificationStatus;

    private Types.ApprovalStatus approvalStatus;

    private boolean enabled;

    private boolean verified = false;

    private String address;
    private String city;
    private String lga;
    private String state;
    private String terminalId;
    private String accountNumber;
    private Double msc;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String transactionPin;

    @Transient
    private boolean hasPin;


    public ClPrincipal toPrincipal() {
        ClPrincipal principal = new ClPrincipal();
        principal.setProfileId(this.id);
        principal.setUsername(this.email);
        principal.setFirstname(this.firstName);
        principal.setLastname(this.lastName);
        principal.setRoleGroup(this.roleGroup.getName());
        principal.setRoles(new ArrayList<>());
        return principal;
    }

    public UserByTerminalDTO toUserTerminalDto(){
        UserByTerminalDTO user = new UserByTerminalDTO();
        user.setUserID(this.id);
        user.setFirstName(this.firstName);
        user.setLastName(this.lastName);
        user.setMsc(this.msc);
        return user;
    }

    public String fullName(){
        return this.firstName + " " + this.lastName;
    }

    public boolean isHasPin() {
        return Objects.nonNull(this.transactionPin) && !this.transactionPin.trim().isEmpty();
    }

}

我希望将此模型用户配置文件的一些细节写入excel表中,并使其可供下载。你觉得我怎么解决这个问题。主要的错误来自这几行,特别是粗体字的那行

AtomicInteger cellNum = new AtomicInteger();
                    mapObj.forEach((key, value) -> {
                        XSSFCell cell = row.createCell(cellNum.getAndIncrement());
                        cell.setCellValue(key);
                        if (value instanceof Integer)
                            cell.setCellValue((Integer) value);
                        else if (value instanceof BigDecimal)
                            cell.setCellValue(((BigDecimal) value).doubleValue());
                        else if (value instanceof Long)
                            cell.setCellValue((Long) value);
                        **else cell.setCellValue((String) value);**
    
                    });
                });

共有1个答案

澹台俊达
2023-03-14

您假设对于els分支,只能是字符串,但从错误来看,它实际上是LinkedHashMap

确保使用的数据都是映射的情况,并相应地编写。

 类似资料: