我正在使用 GSON 库来处理来自 Web 服务的 JSON,但我无法让它工作,我总是得到一个空值。我已经查看了类似的问题,例如 Converting Json to Java such as 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 中所述
关于java - 使用 gson 将 JSON 转换为 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368624/