I am working on a project that calls a REST API to retrieve data.
Once I retrieve the data, I use Google's GSON API in order to convert the JSON data into objects I can use within my application.
Say I have these three types available from the REST API:
Person JSON
{
"person_key_01":"person_value_01",
"person_key_02":"person_value_02",
"person_key_03":"person_value_03"
}
Matching Person.class
public class Person {
private key_01;
private key_02;
private key_03;
// getters and setters
}
Place JSON
{
"place_key_01":"place_value_01",
"place_key_02":"place_value_02",
"place_key_03":"place_value_03"
}
Matching Place.class
public class Place {
private key_01;
private key_02;
private key_03;
// getters and setters
}
Thing JSON
{
"thing_key_01":"thing_value_01",
"thing_key_02":"thing_value_02",
"thing_key_03":"thing_value_03"
}
Matching Thing.class
public class Thing{
private key_01;
private key_02;
private key_03;
// getters and setters
}
What I would like to do is have a single method that will take any of these three JSON strings and convert it to the proper object. I have tried [different variations] of the following with no luck:
public class UtilityClass {
public static Object jsonToObjectOne(String receivedJSON){
Gson gson = new GsonBuilder().create();
Object object = gson.fromJson(receivedJSON, Object.class);
if(object instanceof Person){
return (Person)object;
} else if(object instanceof Place) {
return (Person)object;
} else if(object instanceof Thing) {
return (Person)object;
}
return null;
}
// I also tried this:
public static Object jsonToObjectTwo(String receivedJSON){
Gson gson = new GsonBuilder().create();
Object object = gson.fromJson(receivedJSON, Object.class);
if((Person)object instanceof Person){
return (Person)object;
} else if((Place)object instanceof Place) {
return (Person)object;
} else if((Thing)object instanceof Thing) {
return (Person)object;
}
return null;
}
}
As you can guess, this is not working for me.
Is there a way to take in a String
of one the three types and return a specific Java object of that specific type?
Thanks!