6

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
afx
  • 853
  • 1
  • 9
  • 11
  • 1
    Short answer: No. http://code.google.com/p/google-gson/issues/detail?id=298 – Brian Roach Feb 23 '13 at 23:43
  • Hi Brian, am I right, interpreting your comment and the linked thread, that it is and will in future not possible to serialize local classes and anonymous classes because gson#serialise and gson#deserialise shall be symmetrically? Quite funny, because serialization and deserialization are nearly almost asymmetric – afx Feb 24 '13 at 21:58

1 Answers1

2

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.)

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97