Genesist Genesist - 8 months ago 48
Java Question

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[])
Gson gson = new Gson();
A a = new A();
String j = gson.toJson(t);


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