Search code examples
javaarraysjsonsyntaxjson-simple

Java Syntax: JSONArray array = (JSONArray)obj


I'm learning to Decode JSON files in Java and have come across some Syntax I do not understand. I am also new to Java. Here is the code snippet:

Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;

In my best attempt at Programmer speak, I understand that "JSONArray" is a class. We are instantiating a new JSONArray and calling it "array". We are initializing "array" with the value on the right side of the equal sign.

My question is -- I don't understand what is happening on the right side of the equal sign. Why is "JSONArray" in parenthesis: (JSONArray)obj? I don't understand what is happening here.

Thanks!


Solution

  • Received JSON may, as its outermost structure, be either an "object" (Map) or "array" (List). JSONValue.parse(jsonResult) produces either a JSONObject or JSONArray, depending on which sort of structure is outermost in the jsonResult string. So the parse method must be declared to return some common "ancestor" of those two classes. JSON-Simple is a rather crude JSON kit which has no common superclass for those two classes other than Object.

    Presumably the programmer in this case knows that the received data will always have a JSON "array" as the outermost structure. He initially puts the result from parse in an Object reference (since Object is the formal type returned from parse), then casts that value to JSONArray.

    As Eliot suggests, it would have been better, formally, at least, to include an instanceof test, or, if one used a kit other than JSON-Simple, one could possibly make use of interfaces on a common superclass for the two classes that allowed querying their types.