问题描述
我试图将以下三个方法组合成一个通用解决方案,我尝试了一些编译但在运行时不能很好的想法。
I am trying to make the three following methods into one generic solution, I tried some ideas which compile but don't do well at runtime.
public static List<User> parseToUsers(HttpResponse response) {
ObjectMapper mapper = new ObjectMapper();
String results = parseToString(response);
return mapper.readValue(results, new TypeReference<List<User>>() {});
}
public static List<Record> parseToRecords(HttpResponse response) {
ObjectMapper mapper = new ObjectMapper();
String results = parseToString(response);
return mapper.readValue(results, new TypeReference<List<Record>>() {});
}
public static Record parseToRecord(HttpResponse response) {
ObjectMapper mapper = new ObjectMapper();
String results = parseToString(response);
return mapper.readValue(results, new TypeReference<Record>() {});;
}
我也试过理解这个。
编辑:
这是我到目前为止所提出的:
This is what I came up with so far:
public static <T> T parseJsonResponse(TypeReference<T> type, HttpResponse response) throws DroidException {
ObjectMapper mapper = new ObjectMapper();
String results = parseResponseToString(response);
return readValue = mapper.readValue(results, type);
}
然后我这样称呼它。
parseJsonResponseToList(new TypeReference<List<Record>>() {}, response)
不太满意。有更好的解决方案吗?
Not really satisfieng.Is there a better solution?
推荐答案
那到底是什么是问题吗?你不喜欢它以什么方式?
So what exactly is the problem? In what way do you not like it?
杰克逊有其他方法来构建泛型类型;所以也许正在寻找的是:
Jackson has other ways for constructing generic types; so perhaps what are looking for is along lines of:
public List<T> listOf(String json, Class<T> elementType) {
ObjectMapper mapper = new ObjectMapper(); // should (re)use static instance for perf!
JavaType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, elementType);
return mapper.readValue(json, listType);
}
TypeFactory
可以是用于以编程方式构造使用泛型的类型 - 返回类型是 JavaType
,因为基本Java Class
是类型擦除的。
TypeFactory
实际上用于将 TypeReference
转换为 JavaType
内部也是。
TypeFactory
can be used to programmatically construct types that use generics -- return type is JavaType
, because basic Java Class
is type-erased.TypeFactory
is actually used to convert TypeReference
to JavaType
internally as well.
编辑
关于常规,非收集/映射类型,它非常简单:
As to regular, non-Collection/Map types, it's really quite simple:
public T parseSingle(Class<T> cls, InputStream src) throws IOException {
return mapper.readValue(src, cls);
}
(你也不想把内容读作字符串 - 不仅是它很慢,但很容易弄乱字符编码,所以如果可能的话,请输入 InputStream
或 byte []
代替)
(you also do NOT want to read contents as String -- not only is it slow, but it's easy to mess up character encodings, so if possible, feed InputStream
or byte[]
instead)
这篇关于Java泛型和超类型令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!