首页 > 解决方案 > 具有混合类型(长和字符串)的哈希图时,类 java.lang.Long 无法转换为类 java.lang.String 错误

问题描述

我有 spring boot -camel 应用程序,它连接到 postgre 数据库并从选择查询中返回以下数组:

[{id=1, name=JENNY, country=LB}, {id=2, name=AMIGOSCODE, country=UK}]

id 是bigint数据库中的类型,但是 name 是类型string

执行以下代码时:

@Component
public class InsertRestService extends RouteBuilder {

  

    @Override
    public void configure() throws Exception {
        

        
        rest("/").produces("application.json")
        .get("selectPerson/{name}")//.outType(EmployeeInfo.class)
        .to("direct:selectPerson");

    from("direct:selectPerson")
        .transform().simple("SELECT * FROM person WHERE name=" + "'${header.name}'")
        .log("${body}")
        .to("jdbc:dataSource") //spring boot starter jdbc creates the bean in the registry
        .process(new Processor() {
            public void process(Exchange xchg) throws Exception {
               //the camel jdbc select query has been executed. We get the list of employees.
                ArrayList<HashMap<String, String>> dataList = (ArrayList<HashMap<String, String>>) xchg.getIn().getBody();
                        
                List<EmployeeInfo> employees = new ArrayList<EmployeeInfo>();
                System.out.println(dataList);
                for (HashMap<String, String> data : dataList) {
                    EmployeeInfo employee = new EmployeeInfo();
                    
                    employee.setEmpId(data.get("id"));
                    
                    employee.setEmpName(data.get("name"));
                    
                    employees.add(employee);
                    
                }
                xchg.getIn().setBody(employees)
                ;
            }
        
        })
        .marshal().json(JsonLibrary.Gson)
        .log("${body}");
        
        
     
    }
}

我收到以下错误:

java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.String (java.lang.Long and java.lang.String are in module java.base of loader 'bootstrap')

我认为这是因为 hashmapHashMap<String, String>具有类型字符串,但我不知道该怎么做,因为我在 hashMap 中混合了类型。

我也有一堂课:

public class EmployeeInfo {

    private String empId;
    private String empName;

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    @Override
    public String toString() {
        return "[empId=" + empId + ", empName=" + empName + "]";
    }

}

当尝试将类型更改为empId“long”时,它也不起作用。

我将不胜感激任何帮助!提前致谢!

标签: javapostgresqlhashmapapache-camel

解决方案


你有没有尝试转换

ArrayList<HashMap<String, String>>

ArrayList<HashMap<String, Object>>

在执行 data.get() 时根据您的字段名称发布该内容,您可以通过实例检查将其类型转换为所需的类型。

此外,如果您想检查类型:您可以在每个字段访问之前添加一个日志

Object obj = data.get(<field>);
log(obj.getClass().getName());

希望这会有所帮助。


推荐阅读