Using gson it works with no issues, it will only set the value for name.
public class SO_50688866 {
public static void main(String ... args) {
String json = "{\"name\": \"testname\"}";
Ui ui = new Gson().fromJson(json, Ui.class);
System.out.println(ui.name);
}
public static class Ui {
public String name;
public String title;
}
}
EDIT I
I see you wanted exactly the opposite :)
I don't see that gson support this natively, but I found this answer that could meet your needs: Java to Json validation using GSON
Also I came up with this class that can do a checking of the fields after deserializing the json string.
It has a few caveats like if there is a missing primitive, like an int, it will be initialized to zero so it won't be null. Or if effectively if the fields comes as null in the json.
But perhaps you can adapt it for your needs, like adding a method which takes the names of the fields to check.
public static class CheckNullFields<T>{
@SuppressWarnings("unchecked")
public void check(T obj) throws IllegalAccessException{
Class<T> clazz = (Class<T>) obj.getClass();
Field [] fields = clazz.getDeclaredFields();
for(Field field : fields) {
if(field.get(obj) == null) {
throw new RuntimeException("Null value in field " + field.getName());
}
}
}
}
You would use it like this:
String json = "{\"name\": \"testname\"}";
try {
Ui ui = new Gson().fromJson(json, Ui.class);
new CheckNullFields<Ui>().check(ui);
System.out.println(ui.name);
System.out.println(ui.title);
}catch(Exception e) {
e.printStackTrace();
}