Alexandr
Alexandr

Reputation: 3969

Gson serialization: how to cast generic class and generic data inside it?

An example to make it clearer:

public class GsonDemo {

    public static void main(String[] args) {
        Gson gson = new Gson();

        DataContainer<ExtendedData> dataContainer = new DataContainer<ExtendedData>();
        dataContainer.data = new ExtendedData();
        dataContainer.data.baseData = "base_data";
        dataContainer.data.extraData = "extra_data";

        String json = gson.toJson(dataContainer); // {"data":{"extraData":"extra_data","baseData":"base_data"}}
        System.out.println(json);

        json = gson.toJson(dataContainer, new TypeToken<DataContainer<Data>>() {}.getType());
        System.out.println(json); // i don't want 'extraData' here. Why it steel serializing?
    }

}

And data classes that I use:

class DataContainer<D extends Data> {
    D data;
}

class Data {
    String baseData;
}

class ExtendedData extends Data {
    String extraData;
}

I want to cast DataContainer<ExtendedData> to DataContainer<Data> and serialize it without extraData. I can't actually cast DataContainer<ExtendedData>:

DataContainer<Data> castedDataContainer = (DataContainer<Data>) dataContainer; // Inconvertible types; cannot cast 'DataContainer<ExtendedData>' to 'DataContainer<Data>'

Result, that I expect after instructions TypeToken: {"data":{"baseData":"base_data"}}

But extraData is steel serializing. What did I wrong?

Upvotes: 0

Views: 132

Answers (1)

sargue
sargue

Reputation: 5885

Gson uses reflection while serializing data so a cast won't change anything.

What you want is to control which fields get serialized. You have several alternatives for that:

The last one allows you to act dinamically so it is the most flexible.

Upvotes: 1

Related Questions