举了一个展示我问题的例子。 可能有人有任何想法吗?
线程“main”中的异常java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap无法转换为 Main.main(Main.java:8)中的JSONClassResponse sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:498)at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
public class Main {
public static void main(String[] args) {
GetJSON<JSONClassResponse<JSONClass>> getJSON = new GetJSON<>();
JSONClassResponse<JSONClass> jsonResult = getJSON.get();
System.out.println(jsonResult);
}
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class GetJSON<T> {
public T get() {
String buf = "{errcode:1,data:{value:[v1,v2,v3]}}"; // instant http request
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Type tType = new TypeToken<T>() {
}.getType();
T t = gson.fromJson(buf, tType);
return t;
}
}
import com.google.gson.annotations.SerializedName;
public class JSONClassResponse<T> {
@SerializedName("errcode")
private String errcode;
@SerializedName("data")
private T data;
}
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class JSONClass {
@SerializedName("value")
private List<String> value = null;
}