我可以使用Gson序列化方法本地类和匿名类吗? [英] Can I use Gson to serialize method-local classes and anonymous classes?
问题描述
示例:
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序列化匿名类,但是该论证仅适用于反序列化
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.
推荐答案
FWIW,杰克逊将序列化匿名和本地类就好了.
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"}
}
请注意,杰克逊默认情况下不会像Gson那样通过反射访问非公共字段,但是可以将其配置为这样做.Jackson的方法是使用常规Java属性(通过get/set方法).(将其配置为使用私有字段确实会降低运行时性能,但这仍然比Gson快得多.)
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.)
这篇关于我可以使用Gson序列化方法本地类和匿名类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!