Couple things:
First off, you should always wrap if statements in { } curly brackets.
Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part.getClass() == JSONObject.class){
((JSONObject)part).save(saveTo, "");
}
if (part.getClass() == JSONArray.class){
((JSONArray)part).save(saveTo, "");
}
Secondly, if you only expect one of those if statements to execute, then you should probably use an else if:
Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part.getClass() == JSONObject.class){
((JSONObject)part).save(saveTo, "");
}
else if (part.getClass() == JSONArray.class){
((JSONArray)part).save(saveTo, "");
}
Third, you could use the instanceof operator instead of getting the class:
Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part instanceof JSONObject){
((JSONObject)part).save(saveTo, "");
}
else if (part instanceof JSONArray){
((JSONArray)part).save(saveTo, "");
}
But to answer your question, there isn't a great way to minimize this code, because JSONObject and JSONArray are both direct subclasses of Object. It would be easier if, say, JSONArray was a subclass of JSONObject, but it's not.
But if you find yourself writing this code in multiple places, you should extract it into a function, like this:
void saveJsonThing(Object part, File file)
if (part instanceof JSONObject){
((JSONObject)part).save(saveTo, "");
}
else if (part instanceof JSONArray){
((JSONArray)part).save(saveTo, "");
}
else{
//handle error?
}
}
Then your code can just call that function whenever it needs to save something:
Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
saveJsonThing(part, saveTo);
toStringis a method ofObject{a:"b",c:[{"test":hello world}]}?)