例子:
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 序列化匿名类,但该论证仅对反序列化有效。