密钥正确时,由于ClassCastException,无法在Java中打印LinkedHasMap
我正在测试RESTAPI。下面是我的JSON响应密钥正确时,由于ClassCastException,无法在Java中打印LinkedHasMap,java,hashmap,linkedhashmap,Java,Hashmap,Linkedhashmap,我正在测试RESTAPI。下面是我的JSON响应 [ { "id" : 1, "name" : "Chattagram" }, { "id" : 2, "name" : "Rajshahi" }, { "id" : 3, "name" : "Khulna" }, { "id" : 4, "name" : "Barisal" }, { "id" : 5, "name" : "Sylhet" }, { "id" : 6, "name" : "Dhaka
[ {
"id" : 1,
"name" : "Chattagram"
}, {
"id" : 2,
"name" : "Rajshahi"
}, {
"id" : 3,
"name" : "Khulna"
}, {
"id" : 4,
"name" : "Barisal"
}, {
"id" : 5,
"name" : "Sylhet"
}, {
"id" : 6,
"name" : "Dhaka"
}, {
"id" : 7,
"name" : "Rangpur"
}, {
"id" : 8,
"name" : "Mymensingh"
} ]
我已将列表转换为HashMap列表。我可以访问名称
字段,但在尝试获取id
时,出现以下异常。我不明白为什么会出现这种异常,因为密钥是正确的。我已经给出了调试控制台映像,有人能告诉我问题出在哪里,以及如何访问id
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
源代码:
@Test
public void getEmployees() throws IOException {
final String uri = "http://localhost:8080/public/geocode/divisions";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
restTemplate.getForObject(uri, String.class);
System.out.println(result);
ObjectMapper mapper = new ObjectMapper();
List<Map<String, String>> list = new ArrayList<>();
list = mapper.readValue(result, List.class);
System.out.println(list.get(0));//--------------out put : {id=1, name=Chattagram}
Map<String, String> m = list.get(0);
System.out.println("id : " + m.get("id")); //------------problem line
System.out.println("Name : " + m.get("name")); //------------working fine
System.out.println(list);
}
@测试
public void getEmployees()引发IOException{
最终字符串uri=”http://localhost:8080/public/geocode/divisions";
RestTemplate RestTemplate=新RestTemplate();
String result=restemplate.getForObject(uri,String.class);
getForObject(uri,String.class);
系统输出打印项次(结果);
ObjectMapper mapper=新的ObjectMapper();
列表=新的ArrayList();
list=mapper.readValue(结果,list.class);
System.out.println(list.get(0));//-----------out:{id=1,name=Chattagram}
Map m=list.get(0);
System.out.println(“id:+m.get(“id”);//-----------问题行
System.out.println(“名称:”+m.get(“名称”);//------------工作正常
系统输出打印项次(列表);
}
在问题行中设置断点后,调试变量:
试试看
System.out.println("id : " + Integer.toString(m.get("id"));
Map
,但是id
的值是Integer
。