The following code returns "null" for me.
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 uses reflection under the covers to determine the object structure. The class BagOfPrimitives is in this particular example as being a local class inaccessible by reflection and therefore Gson cannot determine its structure.
Rather make it a standalone or a nested class instead. The following example with nested class works for me:
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With