Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Gson to serialize method-local classes and anonymous classes?

Tags:

java

gson

Example:

import com.google.gson.Gson;

class GsonDemo {

    private static class Static {String key = "static";}
    private class NotStatic {String key = "not static";}

    void testGson() {
        Gson gson = new Gson();

        System.out.println(gson.toJson(new Static()));
        // expected = actual: {"key":"static"}

        System.out.println(gson.toJson(new NotStatic()));
        // expected = actual: {"key":"not static"}

        class MethodLocal {String key = "method local";}
        System.out.println(gson.toJson(new MethodLocal()));
        // expected: {"key":"method local"}
        // actual: null  (be aware: the String "null")

        Object extendsObject = new Object() {String key = "extends Object";};
        System.out.println(gson.toJson(extendsObject));
        // expected: {"key":"extends Object"}
        // actual: null  (be aware: the String "null")        
    }

    public static void main(String... arguments) {
        new GsonDemo().testGson();
    }
}

I would like these serializations especially in unit tests. Is there a way to do so? I found Serializing anonymous classes with Gson, but the argumentation is only valid for de-serialization.

like image 429
afx Avatar asked Nov 13 '22 11:11

afx


1 Answers

FWIW, Jackson will serialize anonymous and local classes just fine.

public static void main(String[] args) throws Exception
{
  ObjectMapper mapper = new ObjectMapper();

  class MethodLocal {public String key = "method local";}
  System.out.println(mapper.writeValueAsString(new MethodLocal()));
  // {"key":"method local"}

  Object extendsObject = new Object() {public String key = "extends Object";};
  System.out.println(mapper.writeValueAsString(extendsObject));
  // {"key":"extends Object"}
}

Note that Jackson by default won't access non-public fields through reflection, as Gson does, but it could be configured to do so. The Jackson way is to use regular Java properties (through get/set methods), instead. (Configuring it to use private fields does slow down the runtime performance, a bit, but it's still way faster than Gson.)

like image 149
Programmer Bruce Avatar answered Nov 15 '22 06:11

Programmer Bruce