以下代码为我返回“ 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));
}
}
解决方法:
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
}
}
}