GSON serialize only some fields of current class

时间:2016-05-11 11:35:18

标签: java serialization gson

I have a class with some attributes and in some cases I need to serialize only some of its fields and in other cases other fields. Let's say:

public class MyClass {

private String a;
private String b;
private String c;
private String d;

//constructor

    public static MyClass fromString(final String string) {
        Gson gson = new Gson();
        MyClass obj = gson.fromJson(string, MyClass.class);
        return obj;
    }

    public String toStringVersion1() {
        final Gson gson = new GsonBuilder().create();
        //here I want to serialize only a and b fields
    }

    public String toStringVersion2() {
        final Gson gson = new GsonBuilder().create();
        //here I want to serialize only c and d fields
    }
}

I tried to use ExclusionStrategy from GSON, I defined a strategy for each version but I have to provide field names as parameter to strategy's constructor:

public class TestExclStrat implements ExclusionStrategy {

    private Set<String> toBeSerialized;

    public TestExclStrat(Set<String> fields) {
        toBeSerialized = fields;
    }

    @Override
    public boolean shouldSkipClass(Class<?> arg0) {
        return false;
    }

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return !toBeSerialized.contains(f.getName());
    }
}

As far as I know, there is no way to get fieldNames at runtime in Java and I can't afford hardcoding name of the fields ("a", "b" for the first strategy and "c" and "d" for the second one). Any ideas?

0 个答案:

没有答案