看起来你只是使用:
private static <T> T fromJson(final String json, final Type type) {
if ( type == null ) {
return null;
}
return gson.fromJson(json, type);
}
如果出于某种正当原因,您无法将null 传递给fromJson 方法,您可以创建一个Void 和void 友好型适配器并将其绑定到您的Gson 实例(属于当然,你不能返回一个void“值”):
final class VoidTypeAdapter
extends TypeAdapter<Void> {
private static final TypeAdapter<Void> voidTypeAdapter = new VoidTypeAdapter();
private VoidTypeAdapter() {
}
static TypeAdapter<Void> getVoidTypeAdapter() {
return voidTypeAdapter;
}
@Override
@SuppressWarnings("resource")
public void write(final JsonWriter out, final Void value)
throws IOException {
out.nullValue();
}
@Override
public Void read(final JsonReader in)
throws IOException {
// Skip the current JSON tokens stream value entirely
in.skipValue();
return null;
}
}
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(Void.class, getVoidTypeAdapter())
.registerTypeAdapter(void.class, getVoidTypeAdapter())
.create();
private static <T> T fromJson(final String json, final Type type) {
return gson.fromJson(json, type);
}
private static String toJson(final Object object, final Type type) {
return gson.toJson(object, type);
}
所以一个简单的测试可能如下所示:
private static void test(final Type type) {
System.out.println(type);
final Object value = fromJson("[\"foo\",\"bar\"]", type);
System.out.println("-\t" + value);
System.out.println("-\t" + toJson(value, type));
}
public static void main(final String... args) {
test(new TypeToken<List<String>>() {}.getType());
test(Void.class);
test(void.class);
}
输出:
java.util.List
- [富,酒吧]
- ["foo","bar"]
类 java.lang.Void
- 空
- 空
无效
- 空
- 空
请注意,类型标记主要用于构建泛型类型的类型信息。在更简单的情况下,您可以使用.class 获取Class<?>:int.class、Integer.class、void.class、Void.class、int[][][][][].class 等。