Reputation:
I have a JSON file where value can either be an object or an array. I have written the following code in Java for reading the file.
public static void getInput() throws IOException, ParseException{
//creates a new JSON parser object.
JSONParser parser = new JSONParser();
File file = new File("my file");
Object ob = parser.parse(new FileReader(file));
JSONObject job = (JSONObject) ob;
JSONArray ja = (JSONArray) job.get("declaration-list");
for (Object o : ja){
JSONObject declared_variable = (JSONObject) o;
JSONObject value = (JSONObject) o;
String dv = (String) declared_variable.get("declared-variable");
long v = (long) value.get("value");
}
I would like to get operator and arguments from value if it is a JSONArray, but there are instances where value is a JSONObject. How do i test for this?
Upvotes: 0
Views: 61
Reputation: 5326
Although there may be better ways but simply use of instanceof
can be helpful.
Object o ...
if( o instanceof JSONObject) {
processJSONObject((JSONObject)o);
} else if (o instanceof JSONArray){
processJSONArray((JSONArray)o);
} else {
// Invalid object type handling
}
Upvotes: 1