java - 具有混合类型(长和字符串)的哈希图时,类 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”时,它也不起作用。
我将不胜感激任何帮助!提前致谢!
解决方案
你有没有尝试转换
ArrayList<HashMap<String, String>>
到
ArrayList<HashMap<String, Object>>
在执行 data.get() 时根据您的字段名称发布该内容,您可以通过实例检查将其类型转换为所需的类型。
此外,如果您想检查类型:您可以在每个字段访问之前添加一个日志
Object obj = data.get(<field>);
log(obj.getClass().getName());
希望这会有所帮助。
推荐阅读
- javascript - Javascript - 如何创建一个对象数组,其中对象的键都具有相同的值
- angular - 如何在不包含角度 6 的情况下从另一个组件调用方法
- java - 无法将应用内产品添加到已发布的应用
- linux - Oracle JDBC 驱动程序是否适用于 Active Directory 身份验证?
- jquery - jQuery 选择一个类的下一个实例
- python - 日期列中的 Python 范围
- c# - 按钮发送命令 SerialPort1_DataReceived (EventArgs e) 发送和接收响应,与不需要它的人产生冲突
- ruby-on-rails - Docker build 说的是无法满足的约束
- angular - AngularJS 6 中的表单
- reporting - Pentaho 报告