Wespen
Wespen

Reputation: 81

Cast to class from JSONObject

I got JSONObject from service response.

Well in case of an error I need to cast it to one of the error classes.

Json is something like

{"message":"This means that the userID is not valid.","name":"UserNotFoundException"}

where name can be any of the exceptions in model package

Can I do this?

Class ex = Class.forName("com.myapp.model.Exceptions." + jsonObject.getString("name"));

How can I cast ex to UserNotFoundException class so I can use its methods i.e. ex.doSomething()

Upvotes: 0

Views: 1628

Answers (3)

Alonso Dominguez
Alonso Dominguez

Reputation: 7858

you aren't actually casting anything in your code, you are retrieving a class instance using a naming convention of your own. You'll need to create an instance of that exception class later on using the message from your JSON object.

Casting is a complete different thing, to get some understanding you can look at this answer.

The thing is, you can't cast a JSON object to a Java class, the same way you can't cast a DOM tree to a Java object tree. What you can do (and everyone does) is to marshal/unmarshal the JSON object to a Java class. This means, creating instances of the Java classes that match the JSON object structure and then map the attributes of that Java class with the attributes of the JSON object.

So, in your code it would look like:

Class ex = Class.forName("com.myapp.model.Exceptions." + jsonObject.getString("name"));
Constructor cons = ex.getConstructor(String.class);
UserNotFouncException unfe = (UserNotFoundException) cons.newInstance(jsonObject.getString("message"));  // here is where actual casting is happening

Note: please, be aware that above code may throw exceptions that you need to guard for.

Upvotes: 0

Prannoy Tank
Prannoy Tank

Reputation: 110

You can use GSON. it easily serializes and de-serializes json data..

For Reference -- > https://code.google.com/p/google-gson/

Upvotes: 0

VM4
VM4

Reputation: 6499

If you really need to do this (although this is something that is usually done very rarely), take a look at reflection: Java how to instantiate a class from string

Upvotes: 2

Related Questions