看起來你只需使用:
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'。 –