I tried using @NotNull
annotation but it did not work. If any field is missing in the JsonString
, it gives null(String)
or zero(int)
. But what I want is if any field is missing in the JsonStr
defined in the class should throw an exception.
Add: My PojoClass
may have object reference or multilevel object reference. I am using Gson for the conversion of the String
to obj.
for more clarification, I have added my code below:
JsonStr:
{
"name":"John",
"id":1,
"roll":100,
"c":{
"city":"Dhaka",
"school":"B. govt. School"
}
}
Code:
public class C {
private String city;
private String school;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
ClassB:
public class B {
private String name;
private int id;
@NotNull
private int roll;
private C c;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
MainClass:
try {
B obj = new B();
String str = "{\"name\":\"John\",\"id\":1,\"c\":{\"city\":\"dhaka\",\"school\":\"school\"}}";
obj = gson.fromJson(str, B.class);
} catch (RuntimeException e) {
System.out.println("exception Message");
}
For the field roll, I used @NotNull
to throw an exception if that field is not present in the JsonStr
but it gives 0 value without throwing any exception.
How can I implement that?
Please don't say this is duplicate, because I have seen these questions: