Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does gson not serialize this tutorial code?

Tags:

java

json

gson

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));


    }

}
like image 332
talloaktrees Avatar asked Mar 25 '26 09:03

talloaktrees


1 Answers

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
        }
    }

}
like image 66
BalusC Avatar answered Mar 27 '26 00:03

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!