Skip to content

Instantly share code, notes, and snippets.

@benjaminaaron
Created May 31, 2016 21:07
Show Gist options
  • Save benjaminaaron/3f34fcd0cc46f3a62dbb4836ec4a06c7 to your computer and use it in GitHub Desktop.
Save benjaminaaron/3f34fcd0cc46f3a62dbb4836ec4a06c7 to your computer and use it in GitHub Desktop.
gson.fromJson + JsonBooleanDeserializer + allFieldsNotNull()
public class AttributesExample {
private String str;
private Double dbl;
private Boolean bool;
public boolean allFieldsNotNull() {
return str != null && dbl != null && bool != null;
}
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new JsonBooleanDeserializer());
Gson gson = builder.create();
String json;
// TEST 1
json = "{" +
"\"str\": \"hi\", " +
"\"dbl\": 2.0, " +
"\"bool\": true" +
"}";
AttributesExample test1 = gson.fromJson(json, AttributesExample.class);
System.out.println(test1.allFieldsNotNull()); // --> TRUE
// TEST 2
json = "{" +
"\"str\": hi, " + // string without " is ok
"\"dbl\": 2., " + // ending on . is ok
"\"bool\": \"true\"" + // true with " is ok
"}";
AttributesExample test2 = gson.fromJson(json, AttributesExample.class);
System.out.println(test2.allFieldsNotNull()); // --> TRUE
// TEST 3
json = "{" +
"\"str\": \"hi\", " +
"\"dbl\": 2.a0, " +
"\"bool\": true" +
"}";
AttributesExample test3 = gson.fromJson(json, AttributesExample.class);
System.out.println(test3.allFieldsNotNull()); // --> NumberFormatException: For input string: "2.a0"
// TEST 4
json = "{" +
"\"str\": \"hi\", " +
"\"dbl\": 2.0, " +
"\"bool\": tre" + // isn't recognized as true or false and is default-casted to false because of the JsonBooleanDeserializer
"}";
AttributesExample test4 = gson.fromJson(json, AttributesExample.class);
System.out.println(test4.allFieldsNotNull()); // --> FALSE
// TEST 5
json = "{" +
"\"str\": \"hi\", " +
"\"bool\": false" +
"}";
AttributesExample test5 = gson.fromJson(json, AttributesExample.class);
System.out.println(test5.allFieldsNotNull()); // --> FALSE, because not all fields were set even so the two fields were set correctly
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment