Created
May 31, 2016 21:07
-
-
Save benjaminaaron/3f34fcd0cc46f3a62dbb4836ec4a06c7 to your computer and use it in GitHub Desktop.
gson.fromJson + JsonBooleanDeserializer + allFieldsNotNull()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AttributesExample { | |
private String str; | |
private Double dbl; | |
private Boolean bool; | |
public boolean allFieldsNotNull() { | |
return str != null && dbl != null && bool != null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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