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

时间:2013-02-23 10:51:24

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

我希望这些序列化特别是在单元测试中。有办法吗? 我找到了Serializing anonymous classes with Gson,但论证只适用于反序列化。

1 个答案:

答案 0 :(得分:1)

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那样通过反射访问非公共字段,但可以配置为执行此操作。 Jackson的方法是使用常规Java属性(通过get / set方法)。 (将其配置为使用私有字段确实会降低运行时性能,但它仍然比Gson快。)