我正在尝试来自 here 的示例,并使用此代码写入文件:
public void Write() {
FileWriter file = null;
try {
JSONObject o = new JSONObject();
JSONObject obj = new JSONObject();
obj.put("name", "mky4ong.com");
obj.put("age", new Integer(100));
JSONObject obj2 = new JSONObject();
obj2.put("name", "mk54yong.com");
obj2.put("age", new Integer(1800));
file = new FileWriter(filename);
JSONArray list = new JSONArray();
list.add(obj);
list.add(obj2);
o.put("messages", list);
file.write(o.toJSONString());
file.flush();
file.close();
} catch (IOException ex) {logger.error("{}", ex.getCause());} finally {try {file.close();} catch (IOException ex) {logger.info("{}",ex.getCause());}}
}
并使用这段代码从同一个文件中读取:
public void Load() {
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(new FileReader(filename));
} catch (IOException | ParseException ex) {logger.info("{}", ex.getCause());}
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject ob = iterator.next();
String name =(String) ob.get("name");
Integer age =(Integer) ob.get("age");
logger.info("name: {}, age: {}", name, age);
}
}
}
但是虽然数据写入成功为 {"messages":[{"name":"mky4ong.com","age":100},{"name":"mk54yong.com","age":1800}]}
,加载时遇到问题。
在这一行 Integer age =(Integer) ob.get("age");
编译器说“Exception in thread "main"java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer”。
我尝试了多种转换方式,但都行不通。为什么会出现这样的错误?
ps: 我正在使用 compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
最佳答案
当您编写 json 文件时,所有附加信息都会丢失(在您的情况下,您使用的 Integer
类型。当您读取它时,JSONParser 将自动使用 Long
遇到没有小数点的数字。尝试在阅读器中使用 Long
。请注意,阅读器对编写器一无所知。它只能读取文件并按其所见进行解释适合。
所以回答你的问题:
Long age =(Long) ob.get("age");
会起作用。
关于java - 在 Java 中加载 JSON : java. lang.ClassCastException : java. lang.Long 无法转换为 java.lang.Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40000460/