我有一个函数接收一个JSON对象,它是一个LinkedHashMap。现在我需要将该输入解析为三个类中的任何一个。这段代码有效(使用杰克逊),但感觉不对。这可以用更好的方式完成吗? Java泛型?
public String handleRequest(Object input)
{
ObjectMapper mapper = new ObjectMapper();
ClassA classA = null;
ClassB classB = null;
ClassC classC = null;
// Maybe A?
try
{
classA = mapper.convertValue(input, ClassA.class);
} catch (Exception e) {}
// Maybe B?
try
{
classB = mapper.convertValue(input, ClassB.class);
} catch (Exception e) {}
// Maybe C?
try
{
classC = mapper.convertValue(input, ClassC.class);
} catch (Exception e) {}
String status = "";
if (classA != null)
status = "Class A";
if (classB != null)
status = "Class B";
if (classC != null)
status = "Class C";
return status;
}
更新:
ClassA
,ClassB
和classC
都在同一个软件包中,看起来与此类似,但有一些小的更改不相同:
public class ClassA
{
String a;
String b;
String c;
// ... getters and setters
}