Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to cast Object to JSONObject or JSONArray depending on the Object

I have been trying a method like this but I can't find any solution:

public static JSONObject or JSONArray objectToJSON(Object object){
    if(object is a JSONObject)
        return new JSONObject(object)
    if(object is a JSONArray)
        return new JSONArray(object)
}

I have tried this:

public static JSONObject objectToJSONObject(Object object){
    Object json = null;
    try {
        json = new JSONTokener(object.toString()).nextValue();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    JSONObject jsonObject = (JSONObject)json;
    return jsonObject;
}

public static JSONArray objectToJSONArray(Object object){
    Object json = null;
    try {
        json = new JSONTokener(object.toString()).nextValue();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    JSONArray jsonObject = (JSONArray)json;
    return jsonObject;
}

But then when I invoke objectToJSONArray(object) I put a JSONObject it crashes casting. So I want a generic method. Someone find any solution?

like image 420
Damia Fuentes Avatar asked Oct 10 '15 15:10

Damia Fuentes


1 Answers

I assume you've seen this question. You can probably just add a check of the type using instanceof before you return from each method, and return null if the Object is not of the type expected. That should get rid of the ClassCastException.

Example:

public static JSONObject objectToJSONObject(Object object){
    Object json = null;
    JSONObject jsonObject = null;
    try {
        json = new JSONTokener(object.toString()).nextValue();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (json instanceof JSONObject) {
        jsonObject = (JSONObject) json;
    }
    return jsonObject;
}

public static JSONArray objectToJSONArray(Object object){
    Object json = null;
    JSONArray jsonArray = null;
    try {
        json = new JSONTokener(object.toString()).nextValue();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (json instanceof JSONArray) {
        jsonArray = (JSONArray) json;
    }
    return jsonArray;
}

Then, you can try both methods, and use the return value of the one that doesn't return null, something like this:

public void processJSON(Object obj){
    JSONObject jsonObj = null;
    JSONArray jsonArr = null;
    jsonObj = objectToJSONObject(obj);
    jsonArr = objectToJSONArray(obj);
    if (jsonObj != null) {
        //process JSONObject
    } else if (jsonArr != null) {
        //process JSONArray
    }
}
like image 156
Daniel Nugent Avatar answered Oct 03 '22 15:10

Daniel Nugent