我有一个json字符串,我应该反序列化到下面的类
class Data <T> {
int found;
Class<T> hits
}
我该怎么做? 这是通常的做法
mapper.readValue(jsonString, Data.class);
但是我怎么提到T代表什么呢?
我有一个json字符串,我应该反序列化到下面的类
class Data <T> {
int found;
Class<T> hits
}
我该怎么做? 这是通常的做法
mapper.readValue(jsonString, Data.class);
但是我怎么提到T代表什么呢?
当前回答
只需在Util类中编写一个静态方法。我正在从文件中读取Json。你也可以给String给readValue
public static <T> T convertJsonToPOJO(String filePath, Class<?> target) throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(new File(filePath), objectMapper .getTypeFactory().constructCollectionType(List.class, Class.forName(target.getName())));
}
用法:
List<TaskBean> list = Util.<List<TaskBean>>convertJsonToPOJO("E:/J2eeWorkspaces/az_workspace_svn/az-client-service/dir1/dir2/filename.json", TaskBean.class);
其他回答
public class Data<T> extends JsonDeserializer implements ContextualDeserializer {
private Class<T> cls;
public JsonDeserializer createContextual(DeserializationContext ctx, BeanProperty prop) throws JsonMappingException {
cls = (Class<T>) ctx.getContextualType().getRawClass();
return this;
}
...
}
您需要为所使用的每个泛型类型创建一个TypeReference对象,并使用该对象进行反序列化。例如:
mapper.readValue(jsonString, new TypeReference<Data<String>>() {});
如果你正在使用scala,并且在编译时知道泛型类型,但不想在所有api层中手动传递TypeReference,你可以使用以下代码(使用jackson 2.9.5):
def read[T](entityStream: InputStream)(implicit typeTag: WeakTypeTag[T]): T = {
//nathang: all of this *crazy* scala reflection allows us to handle List[Seq[Map[Int,Value]]]] without passing
// new TypeReference[List[Seq[Map[Int,Value]]]]](){} to the function
def recursiveFindGenericClasses(t: Type): JavaType = {
val current = typeTag.mirror.runtimeClass(t)
if (t.typeArgs.isEmpty) {
val noSubtypes = Seq.empty[Class[_]]
factory.constructParametricType(current, noSubtypes:_*)
}
else {
val genericSubtypes: Seq[JavaType] = t.typeArgs.map(recursiveFindGenericClasses)
factory.constructParametricType(current, genericSubtypes:_*)
}
}
val javaType = recursiveFindGenericClasses(typeTag.tpe)
json.readValue[T](entityStream, javaType)
}
可以这样使用:
read[List[Map[Int, SomethingToSerialize]]](inputStream)
你可以把它包装在另一个类中,这个类知道你的泛型类型的类型。
Eg,
class Wrapper {
private Data<Something> data;
}
mapper.readValue(jsonString, Wrapper.class);
这里Something是一个具体的类型。每个具体化类型都需要一个包装器。否则Jackson就不知道该创建什么对象。
你要做的第一件事是序列化,然后你可以反序列化。 所以当你序列化时,你应该使用@JsonTypeInfo让jackson把类信息写进你的json数据。你可以这样做: 类数据<T> { int发现; @JsonTypeInfo(使用= JsonTypeInfo.Id.CLASS,包含= JsonTypeInfo.As。财产,财产= " @class”) 类< T > } 然后当你反序列化时,你会发现jackson已经将你的数据反序列化为一个类,你的变量在运行时实际上是命中的。