问题
Example:
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();
}
}
I would like these serializations especially in unit tests. Is there a way to do so? I found Serializing anonymous classes with Gson, but the argumentation is only valid for de-serialization.
回答1:
FWIW, Jackson will serialize anonymous and local classes just fine.
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"}
}
Note that Jackson by default won't access non-public fields through reflection, as Gson does, but it could be configured to do so. The Jackson way is to use regular Java properties (through get/set methods), instead. (Configuring it to use private fields does slow down the runtime performance, a bit, but it's still way faster than Gson.)
来源:https://stackoverflow.com/questions/15039670/can-i-use-gson-to-serialize-method-local-classes-and-anonymous-classes