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
3
Answers
Referencing to @StephenC's... I decided to use his second suggestion.
So adding a constructor to my JsonArray class that will take in an argument of a JSONArray, then I add all elements in the JSONArray to JsonArray
Usage:
What’s Happening
Here you will create
JsonArray.java
class and extend it withJSONArray
.it mean your
JsonArray
is child of parent classJSONArray
.Now you have wrote code like.
JsonArray
is a child, andjsonObj.getJSONArray(key);
is a parent. that was problem.Solution:-
Cast it by child class like.
Basically, what you are trying to do won’t work.
The object returned by
jsonObj.getJSONArray(key)
is clearly aJSONArray
and not aJsonArray
. 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 customJsonArray
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 forJSONArray
. And then do this to wrap theJSONArray
instance that you get; e.g.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 themyFunc
functionality into a domain class or a utility class or something.UPDATE – If I was going to use the wrapper approach, I would do it like this:
You don’t necessarily need to write all of that by hand. Some IDEs can automatically generate a skeleton for a wrapper class from the class that you are trying to wrap.