我正在使用GSON库来形成一个Web服务的
JSON,但我无法使它工作,我总是得到一个null.我已经看过类似的问题,如将Json转换为Java,如
Simple Json to Java convertion using GSON.但我仍然遗漏了一些东西
JSON
{"A":"val1","B":"val2","C":"val3","D":"val4","E":"val5","F":"val6","G":"val7"}
SiteWrapper m = gson.fromJson(json, SiteWrapper.class);
java类
SiteWrapper m = gson.fromJson(json, SiteWrapper.class);
System.out.println(m.getMenu());
static class Site {
static String A;
static String B;
static String C;
static String D;
static String E;
static String F;
static String G;
public String toString() {
return String.format(A,B,C,D,E,F,G);}
public static String getA() {
return A;
}
public static String getB() {
return B;
}
... all the way to getG
public void setA(String A) {
Site.A = A;
}
public void setB(String B) {
Site.B = B;
}
... all the way to setB
和我的包装
class SiteWrapper {
private Site site;
public Site getMenu() { return site; }
public void setMenu(Site site) { this.site = site; }
}
无论我做什么,我得到一个空打印,任何想法?
最佳答案 由于它是一个静态的内部类.正如
docs指出并评论:
As well, if a field is marked as “static” then by default it will be
excluded. If you want to include some transient fields…
你可能想试试
Gson gson = new GsonBuilder()
.excludeFieldsWithModifier()
.create();
此外,由于它是一个内部类,您可能需要更改您的JSON如果您可以:
{
"site":{
"A":"val1",
"B":"val2",
"C":"val3",
"D":"val4",
"E":"val5",
"F":"val6",
"G":"val7"
}
}
正如本post所述