JSONObject에서 HashMap으로 일부 값을 가져 오려고하는데 for 루프의 마지막 행에서 ClassCastException이 계속 발생합니다.
Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
mapEntry.getValue ()를 정수로 명시 적으로 캐스팅하려고 시도했지만 동일한 오류가 계속 발생합니다. 마지막 줄없이 코드를 실행하면 다음 출력이 표시됩니다.
key: peter value: 33
key: somekey value: 11
key: steve value: 38
key: guy value: 22
key: name value: 54
따라서 mapEntry.getValue ()가 정수 또는 정수로 형변환 할 수있는 최소한의 숫자를 인쇄하는 것처럼 보입니다.
JSONObject json = getJsonFromFile(filePath);
HashMap<String, Integer> entries = new HashMap<>();
for (Object obj : json.entrySet()) {
Entry<String, Integer> mapEntry = (Entry<String, Integer>) obj;
System.out.println("key: " + mapEntry.getKey() + " value: " + mapEntry.getValue());
entries.put(mapEntry.getKey(), mapEntry.getValue());
}
이것을 시도하면 :
JSONObject json = getJsonFromFile(filePath);
HashMap<String, Number> entries = new HashMap<>();
for (Object obj : json.entrySet()) {
Entry<String, Number> mapEntry = (Entry<String, Number>) obj;
System.out.println("key: " + mapEntry.getKey() + " value: " + mapEntry.getValue());
entries.put(mapEntry.getKey(), mapEntry.getValue());
}
Number
Integer
및 모두의 수퍼 클래스이므로 Long
잘 컴파일되어야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다