例子:

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();
    }
}

我希望这些序列化,尤其是在单元测试中。有办法吗?
我找到了Serializing anonymous classes with Gson,但是该参数仅对反序列化有效。

最佳答案

FWIW,Jackson可以很好地序列化匿名和本地类。

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"}
}

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

关于java - 我可以使用Gson序列化方法本地类和匿名类吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15039670/

10-13 08:58