简体   繁体   中英

Serialize abstract class with Gson returns null

I have a problem with goggles Gson library. Look at following code:

public abstract class Main { 
    public String foo = "foo";
    public List<String> bar = Arrays.asList( "foo", "bar" );


    @Override
    public String toString( ) {
        Gson gson = new Gson( );
        return gson.toJson( this );
    }

    public static void main( String[] args ) {
        Main main = new Main( ) {
        };
        System.out.println(main.toString( ));
    }
}

It prints null . But I would like it to print {"foo":"foo","bar":["foo","bar"]} which it does, when I remove the abstract identifier and the curly brackets after the creation of Main( ) .

So how do I get the right output for an abstract class?

In case of abstract classes, you will need write your own adapter. See this article on the subject.

Looking at the code, I can see that Gson excludes anonymous inner classes. The best explanation I have is because Gson's philosophy is to support symmetric serialization and deserialization, as explained in this bug :

Don't use double brace initialization. It prevents [de]serialization and Gson is designed for symmetric serialization and [de]serialization.

It is impossible to deserialize an inner class without customization. From the users guide :

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization.

Thus Gson prevents the serialization. You could make the anonymous inner class a static nested class instead, and it would work.

Sorry a bit late into this but for those who don't want to create nested class you can use this:

AbstractPayload payload = new AbstractPayload("field") {};
String result = gson.toJson(payload, AbstractPayload.class)

This worked for my case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM