Gson remove unnecessary nested object fields

别等时光非礼了梦想. 提交于 2019-12-11 00:48:00

问题


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?


回答1:


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.




回答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 = 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;
            }
        }
);


来源:https://stackoverflow.com/questions/37546117/gson-remove-unnecessary-nested-object-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!