Home > database >  Cannot cast JSONArray to another JSONArray extended class
Cannot cast JSONArray to another JSONArray extended class

Time:12-31

I have a custom class in Java which extends to JSONArray like the one below

public class JsonArray extends JSONArray {
    
    public void myFunc(){}

}

Now I have a JSONObject that contains JSONArrays in it and I want to cast those JSONArrays to my custom JsonArray class so I can call myFunc() on it

JsonArray array = (JsonArray) jsonObj.getJSONArray(key);
array.myFunc();

But I keep getting an error in my log saying:

JSONArray cannot be cast to JsonArray

Note: I'm running this on Android Studio and this is not my actual code, it's just a replica, so in this case, we should assume all variables are initialized

CodePudding user response:

What's Happening

Here you will create JsonArray.java class and extend it with JSONArray. it mean your JsonArray is child of parent class JSONArray.

Now you have wrote code like.

JsonArray array = (JsonArray) jsonObj.getJSONArray(key);

JsonArray is a child, and jsonObj.getJSONArray(key); is a parent. that was problem.

Solution:-

Cast it by child class like.

JsonArray array = (JsonArray) new JsonArray();

CodePudding user response:

Basically, what you are trying to do won't work.

The object returned by jsonObj.getJSONArray(key) is clearly a JSONArray and not a JsonArray. And no type cast is going to change the actual type of an object. That is just not possible in Java. A reference type to reference type cast in Java does not change the actual class of the object.

If you want to arrange that you can use the result of jsonObj.getJSONArray(key) as your custom JsonArray type, you are going to have to create it with that type in the first place.

How?

  • Possibly using a JSON binding with a custom object mapper. (But I have my doubts that approach will work.)

  • Possibly by making your JsonArray a wrapper class for JSONArray. And then do:

    JsonArray array = new JsonArray(jsonObj.getJSONArray(key));
    

    or something like that.

  • Possibly some other way.

The best way will depend on the actual JSON library you are using and how you are instantiating the JSON classes ... like jsonObject in your example.

But it is probably simpler if you don't try to subclass JSONArray like this. IMO, it is only making things difficult. Instead, just put the myFunc functionality into a domain class or a utility class or something.

  • Related