【发布时间】:2019-08-21 06:50:54
【问题描述】:
我有以下方法:
public <T> T deserialise(String payload, Class<T> expectedClass) {
try {
return mapper.readValue(payload, expectedClass);
} catch (IOException e) {
throw new IllegalStateException("JSON is not valid!", e);
}
}
我可以使用deserialise("{\"foo\": \"123\"}", Foo.class) 拨打电话。
如果我想创建一个从String 到Class 的映射,然后遍历这个映射以将字符串反序列化为对象,我应该使用什么类型?
例如,我想要类似的东西:
Map<String, Class?> contents = ImmutableMap.of(
"{\"foo\": \"123\"}", Foo.class,
"{\"bar\": \"123\", \"bar2\": \"123\"}", Bar.class
);
然后我希望能够:
for (Map.Entry<String, Class?> e : contents.entrySet) {
Class? obj = deserialise(e.getKey(), e.getValue());
}
我应该用什么代替Class??
更新:
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Class<?>> contents = ImmutableMap.of(
"{\"foo\": \"123\"}", Foo.class,
"{ \"color\" : \"Black\", \"type\" : \"BMW\" }", Bar.class
);
for (Map.Entry<String, Class<?>> e : contents.entrySet()) {
try {
Object obj = objectMapper.readValue(e.getKey(), e.getValue());
System.out.println(obj);
} catch (IOException ex) {
ex.printStackTrace();
}
}
更新 #2:
ObjectMapper objectMapper = new ObjectMapper();
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
T typeClass = Foo.class; // TODO: fix syntax error
try {
Class<?> obj = objectMapper.readValue(json, typeClass); // TODO: fix error and cast obj to Foo.class using typeClass
} catch (IOException e) {
e.printStackTrace();
}
【问题讨论】:
标签: java generics polymorphism