Skip to content Skip to sidebar Skip to footer

Gson Remove Unnecessary Nested Object Fields

I am trying to serialize an object. I have the following structure: Class A{ String aField1; String aField2; B bObj; } Class B{ String bField1; String bField2; String bField3;

Solution 1:

Change your Serialize class like this way.

publicclassAimplementsSerializable{
    String aField1;
    String aField2;
    B bObj;

    classB{
        String bField1;
        String bField2;
        String bField3;
    }
}

Just remove the extra fields. It will not make any problem.

Solution 2:

You can mark bField2 and bField3 as transient or use the annotation @Expose(serialize = false).

Or you can customize your serialization exclusion strategy. Sample code:

GsonBuilder builder = newGsonBuilder();
Typetype = newTypeToken <A>(){}.getType();
builder.addSerializationExclusionStrategy(
        newExclusionStrategy() {
            @OverridepublicbooleanshouldSkipField(FieldAttributes fieldAttributes) {
                return fieldAttributes.getName().equals("bField2") ||
                            fieldAttributes.getName().equals("bField3");
            }
            @OverridepublicbooleanshouldSkipClass(Class<?> aClass) {
                returnfalse;
            }
        }
);

Post a Comment for "Gson Remove Unnecessary Nested Object Fields"