Java 使用 gson 反序列化时将默认值设置为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30216317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting Default value to a variable when deserializing using gson
提问by Arun
I am trying to convert JSONto Java object. When a certain value of a pair is null
, it should be set with some default value.
我正在尝试将JSON转换为 Java 对象。当一对的某个值是 时null
,应该设置一些默认值。
Here is my POJO:
这是我的POJO:
public class Student {
String rollNo;
String name;
String contact;
String school;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
Example JSON object:
JSON 对象示例:
{
"rollNo":"123", "name":"Tony", "school":null
}
So if school is null
, I should make this into a default value, such as "school":"XXX"
. How can I configure this with Gsonwhile deserializing the objects?
因此,如果 school is null
,我应该将其设为默认值,例如"school":"XXX"
. 如何在反序列化对象时使用Gson配置它?
回答by Stephen C
I think that the way to do this is to either write your no-args constructor to fill in default values, or use a custom instancecreator. The deserializer should then replace the default values for all attributes in the JSON object being deserialized.
我认为这样做的方法是编写您的无参数构造函数来填充默认值,或者使用自定义实例创建者。然后,反序列化器应该替换被反序列化的 JSON 对象中所有属性的默认值。
回答by durron597
If the null
is in the JSON, Gson is going to override any defaults you might set in the POJO. You couldgo to the trouble of creating a custom deserializer, but that might be overkill in this case.
如果null
在 JSON 中,Gson 将覆盖您可能在 POJO 中设置的任何默认值。您可能会遇到创建自定义反序列化器的麻烦,但在这种情况下这可能有点过头了。
I think the easiest (and, arguably best given your use case) thing to do is the equivalent of Lazy Loading. For example:
我认为最简单的(并且,根据您的用例可以说是最好的)要做的事情相当于Lazy Loading。例如:
private static final String DEFAULT_SCHOOL = "ABC Elementary";
public String getSchool() {
if (school == null) school == DEFAULT_SCHOOL;
return school;
}
public void setSchool(String school) {
if (school == null) this.school = DEFAULT_SCHOOL;
else this.school = school;
}
Note:The big problem with this solution is that in order to change the Defaults, you have to change the code. If you want the default value to be customizable, you should go with the custom deserializer as linked above.
注意:此解决方案的一个大问题是,为了更改默认值,您必须更改代码。如果您希望默认值可自定义,您应该使用上面链接的自定义解串器。
回答by Shivam Mathur
You can simply make a universal function that checks for null
您可以简单地制作一个检查 null 的通用函数
model.SchoolName= stringNullChecker(model.SchoolName);
public static String stringNullChecker(String val) {
if (null == val) val = "";
return val;
}