I have a class which contains various fields and they could be accessed with the help of getters and setters like the following
public class Student {
private String name;
private int age;
private int sibblingsCount;
private String elderSibblingName;
private String youngerSibblingName;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.name;
}
public void setAge(int age) {
this.age = age;
}
public void setSibblingsCount(int count) {
this.sibblingsCount = count;
}
public int getSibblingsCount() {
return this.sibblingsCount;
}
public void setElderSibblingName(String name) {
this.elderSibblingName = name;
}
public String getElderSibblingName() {
return this.elderSibblingName;
}
public void setYoungerSibblingName(String name) {
this.youngerSibblingName = name;
}
public void getYoungerSibblingName() {
return this.youngerSibblingName;
}
public String getStudentDetails() {
JSONObject json = new JSONObject();
if(name != null && !name.isEmpty()) {
json.put("name", this.name);
}
if(this.age != 0) {
json.put("age", this.age);
}
if(this.sibblingsCount != 0) {
json.put("sibblingsCount", this.sibblingsCount);
}
if(this.elderSibblingName != null && !this.elderSibblingName.isEmpty()) {
json.put("elderSibblingName", this.elderSibblingName);
}
if(this.youngerSibblingName != null && !this.youngerSibblingName.isEmpty() {
json.put("youngerSibblingName", this.youngerSibblingName);
}
return json.toString();
}
}
All I need is to pack the valid fields in the class Student
. The field is said to be valid when it contains some value in it. Say age
should not be 0
and it must be a valid number. Say elderSibblingName
it must not be null or empty. How to check for valid fields while packing the resultant json.
It is really painful to check for validity against each and every filed of the class which makes the code looks clumsy when there are too many fields in the class. Any suggestions to improve is most welcome !!
Thanks in advance :-)
Aucun commentaire:
Enregistrer un commentaire