我可以使用Gson序列化方法本地类和匿名类吗?

afx*_*afx 5 java gson

例:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这些序列化特别是在单元测试中.有办法吗?我发现使用Gson序列化匿名类,但论证仅对反序列化有效.

Pro*_*uce 2

FWIW,杰克逊将很好地序列化匿名类和本地类。

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"}
}
Run Code Online (Sandbox Code Playgroud)

请注意,默认情况下 Jackson 不会像 Gson 那样通过反射访问非公共字段,但可以将其配置为这样做。Jackson 方法是使用常规 Java 属性(通过 get/set 方法)。(将其配置为使用私有字段确实会稍微降低运行时性能,但它仍然比 Gson 快得多。)