简体   繁体   English

如何修复 class java.util.LinkedHashMap 无法转换为 class Z93F725A07428BString.3321C886F46D4 错误。

[英]how to fix class java.util.LinkedHashMap cannot be cast to class java.lang.String error

So, I am trying to build a report.所以,我正在尝试建立一个报告。 The details of some certain type of users need to be written in an excel file.某些特定类型用户的详细信息需要写入 excel 文件中。 On hitting the endpoint it returns 500 with the following stacktrace.在到达端点时,它返回 500 并带有以下堆栈跟踪。

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)
     

Here is the helper class that is throwing the error这是抛出错误的助手 class

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);

                });
            });

I have checked the internet and none of what I have seem so far seems to be solving my problems.我已经检查了互联网,到目前为止我所看到的似乎都没有解决我的问题。 There is a List in the models as seen below模型中有一个列表,如下所示

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();
    }

}

It is some of the details of this model UserProfile that I want to write into an excel sheet and make it available for download.我想将这个 model 用户配置文件的一些细节写入 excel 表并使其可供下载。 How do you think i solve the problem.你认为我如何解决问题。 The major error is coming from these lines particularly the one in bold主要错误来自这些行,尤其是粗体字

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);**
    
                    });
                });

You're making an assumption that for the else branch, the value can only be a String , but from the error it looks like it is in fact a LinkedHashMap .您假设else分支的value只能是String ,但从错误来看,它实际上是LinkedHashMap

Make sure that whatever data you work with, you also treat the case where the value is a Map and write that accordingly.确保您使用的任何数据,您还处理value Map的情况并相应地写入。

暂无
暂无

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

相关问题 class java.util.LinkedHashMap cannot be cast to class java.lang.String (java.util.LinkedHashMap and java.lang.String - class java.util.LinkedHashMap cannot be cast to class java.lang.String (java.util.LinkedHashMap and java.lang.String 如何修复“java.lang.ClassCastException:类 java.util.LinkedHashMap 无法转换为类”错误? - How to fix 'java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class' error? 在使用Java 8和Java 11时,如何修复&#39;class java.util.LinkedHashMap无法强制转换为类&#39; - How to fix 'class java.util.LinkedHashMap cannot be cast to class' when using Java 8 and Java 11 class java.util.LinkedHashMap 不能转换为 class [...] - class java.util.LinkedHashMap cannot be cast to class [...] java.lang.ClassCastException:无法将java.util.LinkedHashMap转换为特定类 - java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to Specific class 线程“main”java.lang.ClassCastException 中的异常:类 java.util.LinkedHashMap 无法转换为类 java.util.List - Exception in thread "main" java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class java.util.List java.lang.ClassCastException:无法强制转换java.util.LinkedHashMap - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast Java Stream:类 java.util.LinkedHashMap 不能转换为类 RealmRole - Java Stream: class java.util.LinkedHashMap cannot be cast to class RealmRole ArrayList的迭代器错误:无法将java.util.LinkedHashMap强制转换为MyObject - Iterator error for ArrayList: java.util.LinkedHashMap cannot be cast to MyObject java.util.LinkedHashMap 不能转换为类 com.profile.model.Profile - Spring Boot - java.util.LinkedHashMap cannot be cast to class com.profile.model.Profile - Spring Boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM