Java中如何判断Profiles对象是否为空,避免空指针异常?
解决空指针异常:判断profiles对象是否为空
问题场景
调用数据库API返回的JSON数据示例如下:
[{"profiles":{"testexample":{"addresses":[{"city":"","street1":"","street2":"apt 320"}],"addressType":"HOME","city":"","dateOfBirth":"","emailAddress1":"","emailAddress2":"","emailAddresses":[{"email":"","preferred":1,"type":"BUSINESS"},{"email":"","preferred":0,"type":"PERSONAL"}],"firstName":"","lastName":"","phoneNumber":"","phoneNumbers":[],"phoneType":"HOME","postalCode":"","preferred":1,"street1":"","street2":""}}]
现有Java类结构如下(已省略非关键部分):
public class Account { @JsonProperty("profiles") private Profiles profiles; @JsonProperty("profiles") public Profiles getProfiles() { return profiles; } @JsonProperty("testexample") public void setProfiles(Profiles profiles) { this.profiles = profiles; } }
public class Profiles { @JsonProperty("testexample") private Profile testExample; @JsonProperty("testexample") public Profile getTestExample() { return testExample; } @JsonProperty("testexample") public void setTestExample(Profile testExample) { this.testExample = testExample; } }
public class Profile { @JsonProperty("dateOfBirth") private String dateOfBirth; @JsonProperty("dateOfBirth") public String getDateOfBirth() { return dateOfBirth; } @JsonProperty("dateOfBirth") public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } }
当前代码逻辑在profiles非空时正常运行,但调用response.getProfiles().getTestExample().getDateOfBirth()时,若中间任意对象为空,会抛出空指针异常:
Account response = access.lookup(id, type); // 数据库查询逻辑正常 // 直接调用嵌套方法会触发空指针 // response.getProfiles().getTestExample().getDateOfBirth();
需要通过判断getProfiles()返回对象是否为空,跳过后续内部方法调用,避免异常。
解决方案
1. 逐层空判断(最直接的方式)
在调用嵌套方法前,逐层检查每个对象是否为null:
Account response = access.lookup(id, type); String dateOfBirth = null; Profiles profiles = response.getProfiles(); if (profiles != null) { Profile testExample = profiles.getTestExample(); if (testExample != null) { dateOfBirth = testExample.getDateOfBirth(); } } // 使用dateOfBirth,无需担心空指针
2. 使用Optional类(Java 8+ 优雅写法)
利用Java 8引入的Optional类简化空判断,链式调用更简洁:
Account response = access.lookup(id, type); String dateOfBirth = Optional.ofNullable(response.getProfiles()) .map(Profiles::getTestExample) .map(Profile::getDateOfBirth) .orElse(null); // 或指定默认值,比如orElse("")
3. 修改Jackson配置,自动初始化空对象
如果希望反序列化时自动为null的对象创建空实例(而非保留null),可以配置Jackson的DeserializationFeature:
ObjectMapper objectMapper = new ObjectMapper(); // 开启反序列化时为null的对象创建空实例 objectMapper.enable(DeserializationFeature.CREATE_NULL_CONTAINERS); objectMapper.setDefaultSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
配置后,即使JSON中profiles为空,Jackson也会创建空的Profiles实例,后续调用getTestExample()等方法不会返回null(需确保类有无参构造方法)。
内容的提问来源于stack exchange,提问作者camach828
相关产品推荐
相关产品推荐

