5

例子:

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

我想要这些序列化,尤其是在单元测试中。有没有办法这样做?我发现使用 Gson 序列化匿名类,但该论证仅对反序列化有效。

4

1 回答 1

1

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

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

于 2013-04-03T06:12:35.340 回答