简体   繁体   中英

Serialize inner class with GSON in JAVA

I want to serialize a class which contains an inner class with GSON. I have already checked it is important the inner class be static. I have made it static, but my code does not serialize it.

The class I want to serialize:

public class A{

    static class B{
        public String b; 

        public B() {}
    }

    private int data1 = 100;
    private String data2 = "hello";
    private List<String> list = new ArrayList<String>() {
      {
        add("String 1");
        add("String 2");
        add("String 3");
      }
    };

    public A(){

    }
}

The code which make the seralization:

public class json 
{

    public static void main(String args[])
    {
        try
        {
            Gson gson = new Gson();
            A a = new A();
            String j = gson.toJson(t);

            System.out.println(j);
    }
}

The result:

{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}

The problem is that the result does not contain the inner class serialization.

How can I solve this problem?

Thank you so much for help!

You don't have a field of type B inside A so there's nothing to serialize.

You'd need something like ...

public class A {
    ...
    private B b;
    ...
    public A() {
        b = new B();
        b.b = "Some String";
    }
    ...
}

This is the suitable link . It defines the way to do this but making the inner class as static is the recommended option.

Since your B class does not have any values it is not serialized. To serialize that,

You may configure the gson builder with:

 GsonBuilder gsonBuilder = new GsonBuilder().serializeNulls();
 Gson gson=gsonBuilder.create();
 gson.toJson(a);

Here is the link: https://github.com/google/gson/blob/master/UserGuide.md#null-object-support

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM