我正在开发一个调用REST API来检索数据的项目。
检索数据后,我使用Google的GSON API将JSON数据转换为可在我的应用程序中使用的对象。
假设我在REST API中提供了这三种类型:
人JSON
{
"person_key_01":"person_value_01",
"person_key_02":"person_value_02",
"person_key_03":"person_value_03"
}
匹配Person.class
public class Person {
private key_01;
private key_02;
private key_03;
// getters and setters
}
放置JSON
{
"place_key_01":"place_value_01",
"place_key_02":"place_value_02",
"place_key_03":"place_value_03"
}
匹配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"
}
匹配Thing.class
public class Thing{
private key_01;
private key_02;
private key_03;
// getters and setters
}
我想要做的是使用一个方法来获取这三个JSON字符串中的任何一个并将其转换为正确的对象。我尝试了下面的[不同变化]没有运气:
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;
}
}
你可以猜到,这对我不起作用。
有没有办法接受这三种类型中的String
并返回该特定类型的特定Java对象?
谢谢!