问题:
When trying to parse the following JSON string using the json.simple library:
[
{"id" : "6d7662a9.f8ba04"},
{"id" : "2da98cc2.145ba4"},
{"id" : "45492640.a17d...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
When trying to parse the following JSON string using the json.simple library:
[
{"id" : "6d7662a9.f8ba04"},
{"id" : "2da98cc2.145ba4"},
{"id" : "45492640.a17d68"}
]
I get this exception:
java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONArray
This is how I'm doing it:
JSONArray json = (JSONArray) new JSONParser().parse(jsonString);
The JSON string is an array so not sure why that exception is thrown.
There are several similar questions here but in their cases, they were trying to cast a JSONObject
to a JSONArray
so it makes sense that an exception is thrown but in this case, it looks correct.
-----------------EDITS-----------------
I added a line to print the class of the object, like this:
Object json = new JSONParser().parse(jsonString);
System.out.println(json.getClass());
That prints the following line:
class org.json.simple.JSONArray
and in the next line, I have this if:
if(json instanceof JSONArray) {
System.out.println("This is a JSONArray");
}
But it does not access the if, so it is really weird, because first I check that the object is a JSONArray but it does not print "This is a JSONArray"
回答1:
You say you are getting this:
java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast
to org.json.simple.JSONArray
Note that the fully qualified class names look identical. If that message was transcribed accurately, and the names are identical1, it means that you have two versions of the JSONArray
class loaded into your JVM!
This is possible in a JVM where the application or the framework has multiple class loaders, and you have managed to load the class in more than one class loader. For example, this could happen if you have the JSON library JAR file BOTH in a web container's shared library directory AND in a webapp's WAR file.
The thing is that the runtime type of a class is identified by the classes FQN and the classloader. Two classes with the same FQN loaded in different class loaders are different types, even if the bytecodes are identical. This means that they are not assignment compatible, and it leads to weird (but correct!) class cast failures.
Solution:
- Look at the web container file tree on your execution platform to find multiple copies of the JSON JAR file.
- Remove the problematic copy(s) from either the shared lib directory or all of the WAR files.
1 - A really obscure alternative explanation is that the names look the same due to "homoglyphs" but are actually different. But in this context, I think we can discount that explanation as implausible.
回答2:
It should be like
Object obj = new JSONParser().parse(jsonString);
JSONArray json = new JSONArray();
json.add(obj);