Java - GSON nested serialisation

43 Views Asked by At

the following "issue" I have come across and would like to resolve:

Say you have the following two objects A, B like so:

public class A {
    public Double att1;
    public Double att2;
    
    @Override
    public String toString() {
        GsonBuilder builder = new GsonBuilder();
        builder.serializeSpecialFloatingPointValues();
        builder.serializeNulls();
        
        Gson gson = builder.create();
        
        return gson.toJson(this);
    }
}

public class B {
    
    public A var1;
    public Double var2;
    
    @Override
    public String toString() {
        GsonBuilder builder = new GsonBuilder();
        builder.serializeSpecialFloatingPointValues();
        builder.serializeNulls();
        
        Gson gson = builder.create();
        
        return gson.toJson(this);
    }
}

The serialisation of B into JSON works fine but the output will look something like this:

{"var1":{"att1":{"value":30.0}, "att2":{"value":50.0}...}

Is there a way to get rid of the extra level of nesting where the value in the nested object A is directly assigned to the attribute, i.e. {"var1":{"att1":30.0, "att2":50.0}...} ?

0

There are 0 best solutions below