Java中将JSON反序列化为泛型对象
将嵌套List的Map转换为Json应该都没什么问题,使用Gson和Jackson都能实现,在Gson中使用new Gson().toJson()方法,在Jackson中使用new ObjectMapper().writeValueAsString()即可。将json转换为形如Map<String,List>的时候遇到了一点问题,虽然返回类型是Map<String,List<Long>>但是,Map的value的值却并不是List<Long>,而是Integer类型的,这里面显然是有问题的,查看Jackson的源码和Gson的源码发现将json反序列化为对象确实有两个方法,一种适用于泛型对象,一种适用于非泛型的一般对象。 使用Gson在gson中将json字符串转反序列化为对象有两个方法: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 /** * This method deserializes the specified Json into an object of the specified class. It is not * suitable to use if the specified class is a generic type since it will not have the generic * type information because of the Type Erasure feature of Java. Therefore, this method should not * be used if the desired type is a generic type. Note that this method works fine if the any of * the fields of the specified object are generics, just the object itself should not be a * generic type. For the cases when the object is of generic type, invoke * {@link #fromJson(String, Type)}. If you have the Json in a {@link Reader} instead of * a String, use {@link #fromJson(Reader, Class)} instead. * * @param <T> the type of the desired object * @param json the string from which the object is to be deserialized * @param classOfT the class of T * @return an object of type T from the string. Returns {@code null} if {@code json} is {@code null}. * @throws JsonSyntaxException if json is not a valid representation for an object of type * classOfT */public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException { Object object = fromJson(json, (Type) classOfT); return Primitives.wrap(classOfT).cast(object); } /** * This method deserializes the specified Json into an object of the specified type. This method * is useful if the specified object is a generic type. For non-generic objects, use * {@link #fromJson(String, Class)} instead. If you have the Json in a {@link Reader} instead of * a String, use {@link #fromJson(Reader, Type)} instead. * * @param <T> the type of the desired object * @param json the string from which the object is to be deserialized * @param typeOfT The specific genericized type of src. You can obtain this type by using the * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for * {@code Collection<Foo>}, you should use: * <pre> * Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType(); * </pre> * @return an object of type T from the string. Returns {@code null} if {@code json} is {@code null}. * @throws JsonParseException if json is not a valid representation for an object of type typeOfT * @throws JsonSyntaxException if json is not a valid representation for an object of type */ @SuppressWarnings("unchecked") public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException { if (json == null) { return null; } StringReader reader = new StringReader(json); T target = (T) fromJson(reader, typeOfT); return target; }