我有一个JSON 字符串:
{
"_id": -1,
"create_date": 0,
"update_date": 0,
"description": "test",
"active": true
}
在 Java 中,我尝试使用 org.json.simple.parser.JSONParser 解析它:
JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(phoneJSON);
我尝试检索 _id
字段值:
String s_id = ((String) jsonObject.get("_id"));
但是遇到如下异常:
java.lang.Long cannot be cast to java.lang.String
此外,如果我在控制台中显示字段值:
System.out.println("print value - _id: "+jsonObject.get("_id"));
我得到:
print value - _id: -1
在控制台输出。
我看过这篇文章:
java.lang.Long cannot be cast to java.lang.String
但这对我没有帮助。
我不明白什么?
最佳答案
您必须使用 .toString()
方法将 Long 转换为 String。
String strLong = Long.toString(jsonObject.get("_id")));
Returns a String object representing this Long's value.
此外,println
在控制台输出值的原因是因为 PrintStream.println
有一个重载 takes一个 Object
,然后调用它的 toString
方法。
关于java - 使用 Java 异常转换有效的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30534324/