Sorry if the title is a bit confusing, I didn't really know how to word what I wanted to ask.
Basically, I am making an api call to a database that returns data as such:
[{"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":"***"}]
The code I have below works fine when the database returns a non-empty profiles {}. I have the following Java classes that looks like the following:
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;
}
}
So what I want to do when I get the data is check whether the getProfiles() returns empty, so I don't make the calls to anything within that object.
Please note, for the sake of simplicity I omitted other parts of the classes to focus primarily on what I wanted
This is what I have so far, and it works when the profiles {} is not empty
Account response = access.lookup(id, type); //This is to grab the response from the database, which is working.
response.getProfiles(); //This is the part that works when it has a profiles {} not empty, but fails on empty.
So what happens is that I don't get an error for response.getProfiles(), but if I tried to do response.getProfiles().getDateOfBirth(), it won't work because it will give a null pointer exception since the dateOfBirth isn't there.
I want to avoid calling anything within response.getProfiles() by skipping it if it's empty.
1条答案
按热度按时间sulc1iza1#
你需要一些基本的空值检查。最基本的方法是分配一个新变量并检查。
更“现代”的函数式Java方法是使用
Optional
类。(关于您的示例的注意事项:在Account类中,您有以下代码。
这似乎是一个不正确的
@JsonProperty
注解,可能会导致一些问题。也就是说,没有必要注解getter和setter。字段上的一个注解就足够了。)