【发布时间】:2020-08-28 23:49:08
【问题描述】:
我查询数据库并将其映射到类
MyDataClass myDataClass = myDataDao.findMyDataByAccountNumber(accountNumber);
我把它映射到像这样的其他类
MyOtherDataclass myOtherDataClass = new MyOtherDataClass();
myOtherDataClass.setBirthDate(myDataClass.getBirthDate().toString);
我知道myDataClass.getBirthDate() 为空,因为我的数据库中的birthdate 值为空。
如果我在数据库中将值插入birthdate,那么它是正常的,一切正常。但如果它没有价值,而不是抛出java.lang.NullPointerException: null,我想在json中将它设置为null
我希望 json 中的结果是这样的
{
AccountNumber: "12313",
BlaBla: "blabla",
BirthDate: null,
}
================================================ ==============================
找出问题所在。
我在myOtherDataClass.getBirthDate().toString() 上使用.toString(),所以它抛出空指针。因为myDataClass 中的birthDate 为空。对不起,这是我的错。
解决了
myOtherDataClass.setBirthDate(myDataClass.getBirthDate() != null ? myDataClass.getBirthDate().toString() : null);
【问题讨论】:
-
什么是抛出空指针?吸气剂?请使用 stacktrace 发布您的日志
-
编写一个处理器来处理每个值的空值。
-
@ThomasAndolf 是的,我已经编辑了帖子。谢谢。
-
这里真正的问题是为什么
myOtherDataClass将日期存储为字符串?不要那样做。尽量使用原始类型,只在需要打印或显示时才转换。 -
如果您发布了堆栈跟踪,所有这些都可以在一秒钟内被指出。
标签: java postgresql spring-boot spring-rest