2

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

I am trying to serialze class A and B objects to send them to server. When I am serializing Class A object, it gives me

{
 aField1: "abc",
 aField2: "def",
 B: {
    bField1: "mnp",
    bField2: "qrt",
    bField3: "xyz",
    }
}

And serializing Class B obj:

{
 bField1: "mnp",
 bField2: "qrt",
 bField3: "xyz",
}

But I want Class A object like this:

{
 aField1: "abc",
 aField2: "def",
 B: {
    bField1: "mnp"
    }
}

I am currently using GSON library to accomplish this. I want to remove extra key value pairs when interacting with server. How can I do this?

Abhishek Lodha
  • 737
  • 2
  • 7
  • 30

2 Answers2

0

Change your Serialize class like this way.

public class A implements Serializable{
    String aField1;
    String aField2;
    B bObj;

    class B{
        String bField1;
        String bField2;
        String bField3;
    }
}

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

Zahidul Islam
  • 3,180
  • 1
  • 25
  • 35
0

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 = new GsonBuilder();
Type type = new TypeToken <A>(){}.getType();
builder.addSerializationExclusionStrategy(
        new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                return fieldAttributes.getName().equals("bField2") ||
                            fieldAttributes.getName().equals("bField3");
            }
            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        }
);
LittleLittleQ
  • 440
  • 3
  • 7
  • 21