看起来你只需使用:
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” 的, “酒吧”]
类java.lang.Void的
- 空
- 空空隙
- 空
- 空
注意,类型令牌大多采用为泛型类型构建一个类型信息。在更简单的情况下,你可以使用.class
获得Class<?>
:int.class
,Integer.class
,void.class
,Void.class
,int[][][][][].class
等
如果你简单地传递一个空,不是一个空类型定义?在这种情况下,你甚至不能调用gson。fromJson'只是简单地从你的方法中返回'null'。 –