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

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 to be especially performed in unit tests. Is there any way to do this? I found Serializing anonymous classes with Gson , but the argument is valid only for de-serialization.

+4
source share
1 answer

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 will by default not access non-public fields through reflection, as Gson does, but it can be configured for this. Jackson's way is to use the usual Java properties (via get / set methods). (Setting it to use private fields slows down performance, a little, but still faster than Gson.)

0
source

All Articles