以下代码为我返回“null”。
package test;
import com.google.gson.Gson;
class test {
public static void main(String[] args) {
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj = new BagOfPrimitives();
System.out.println(obj.value1 + obj.value2 + obj.value3);
Gson gson = new Gson();
System.out.println(gson.toJson(obj));
}
}
答案 0 :(得分:4)
Gson在封面下使用reflection来确定对象结构。类BagOfPrimitives
在此特定示例中是反射无法访问的本地类,因此Gson无法确定其结构。
而是将其改为独立或嵌套类。以下带有嵌套类的示例适用于我:
public class Test {
public static void main(String[] args) {
BagOfPrimitives obj = new BagOfPrimitives();
System.out.println(obj.value1 + obj.value2 + obj.value3);
Gson gson = new Gson();
System.out.println(gson.toJson(obj));
}
static class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
}