0

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()

Alonso Dominguez
  • 7,750
  • 1
  • 27
  • 37
Wespen
  • 51
  • 5

3 Answers3

2

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

Community
  • 1
  • 1
VM4
  • 6,321
  • 5
  • 37
  • 51
0

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.

Community
  • 1
  • 1
Alonso Dominguez
  • 7,750
  • 1
  • 27
  • 37
0

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

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

Prannoy Tank
  • 110
  • 7