我试图弄清楚如何使用 gson 将 reddit 的 api 响应转换为我可以使用的形式。在我使用一些代码之后
System.out.println(response.toString());
获得输出(稍作编辑)
{"json": {"errors": [], "data": {"modhash": "dosiom5o6abbbb758729039f04762a05778db4aeeeacd8eb4a", "cookie": "14756159,2012-08-21T12:05:05,0971bdec35d71af4073cf56ad82fb0ae7c5fe2d1"}}}
谷歌搜索后,我建立了以下课程
class GSONClass {
private Response jsonresponse;
public Response getJsonresponse() {
return jsonresponse;
}
public void setJsonresponse(Response jsonresponse) {
this.jsonresponse = jsonresponse;
}
public static class Response {
private String[] errors;
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String[] getErrors() {
return errors;
}
public void setErrors(String[] errors) {
this.errors = errors;
}
}
public static class Data {
private String modhash = "hi";
private String cookie;
public String getCookie() {
return cookie;
}
public void setCookie(String cookie) {
this.cookie = cookie;
}
public String getModhash() {
return modhash;
}
public void setModhash(String modhash) {
this.modhash = modhash;
}
}
}
然后我使用:
GSONClass target = new GSONClass();
String json = gson.toJson(response.toString());
GSONClass target = gson.fromJson(json, GSONClass.class);
我做错了什么,因为我收到“java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING”错误。