类java.lang.Long在拥有混合类型(Long和string)的哈希映射时不能强制转换为类java.lang.S



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

[{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 ' ' '时,它不能正常工作。

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

是否尝试转换

ArrayList<HashMap<String, String>>

ArrayList<HashMap<String, Object>>

Post基于你的字段名,当你做data.get()时,你可以通过实例检查将它类型转换为所需的类型。

同样,如果你想检查类型:您可以在每个字段访问前添加日志

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

希望对大家有帮助。

相关内容