gpt4 book ai didi

java - Gson 序列化一个 bean

转载 作者:行者123 更新时间:2023-11-30 07:18:43 24 4
gpt4 key购买 nike

当我有这样的实体时

class Foo
{
private String Bar = "someBarValue";
}

和下面的语句

String json = new Gson().toJson(new Foo());

结果在 { "bar": "someBarValue"}

我有很多遵循标准 java bean 约定的类

class FooBean
{
String getBar() { return "someBarValue"; }
}

和下面的语句

String json = new Gson().toJson(new FooBean());

{} 中的结果

如何使用 Gson 序列化(并最终反序列化,如果我有 setter)FooBean 而不必依赖类的私有(private)成员变量?

最佳答案

这在今天是不可能的。看看Gson Design Document :

Using fields vs getters to indicate Json elements

Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties.

However, there are good arguments to support properties as well. We intend to enhance Gson in a latter version to support properties as an alternate mapping for indicating Json fields. For now, Gson is fields-based.

您可能会考虑的另一件事是序列化/反序列化的概念:为什么要序列化/反序列化一个对象?一般来说,在持久化、通信(即主要是 I/O)之后拥有它的副本。不依赖 getter 和 setter 这样做是有道理的。它们可能会更改对象的内容,因此序列化/反序列化不会实现它们的目标。

关于java - Gson 序列化一个 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com