Skip to content

Instantly share code, notes, and snippets.

@benjaminaaron
Last active April 14, 2022 09:10
Show Gist options
  • Save benjaminaaron/204415077e1c7efe45b20b323c8a83d9 to your computer and use it in GitHub Desktop.
Save benjaminaaron/204415077e1c7efe45b20b323c8a83d9 to your computer and use it in GitHub Desktop.
validate json by reflection before using gson
public class AttributesExample {
private String str = "foo";
private double dbl = 0.8;
private boolean bool = false;
}
import com.google.gson.*;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
Gson gson = new GsonBuilder().create();
String json = "{" +
"\"str\": \"hi\", " +
"\"dbl\": 2.0, " +
"\"bool\": true " +
"}";
if (isValid(AttributesExample.class, json)) {
AttributesExample attributesExample = gson.fromJson(json, AttributesExample.class);
// ...
} else {
// json not valid
}
}
private static boolean isValid(Class cls, String jsonString) {
JsonObject jsonObj = new JsonParser().parse(jsonString).getAsJsonObject();
if (jsonObj.entrySet().size() > cls.getDeclaredFields().length) { // if the json-string has more entries than class has fields, we're already out
return false;
}
for(Field field : cls.getDeclaredFields()) {
if (!jsonObj.has(field.getName())) { // if the json-string has a key that doesn't have a corresponding field in the class, we're out
return false;
}
JsonElement value = jsonObj.get(field.getName());
switch (field.getType().getTypeName()) {
case "java.lang.String":
// nothing to check, everything is ok as string
break;
case "java.lang.Double":
// check if its a double by try-parsing value, if not we're out
break;
case "java.lang.Boolean":
// check if its a boolean by try-parsing value, if not we're out
break;
}
}
return true;
}
}
@benjaminaaron
Copy link
Author

Hi @Vinod-Kumar-S, thanks, I am glad it's useful for you.
Regarding your question, I wrote this 6 years ago, I don't even remember anymore what I created this for back then 😉
I am not sure what you mean about giving examples. The switch case seems to speak for itself by going through the different types that the field can have 🤔 I guess my intention with those comments was to try parsing these values as Double/Boolean to see if that works or creates an exception.

@Vinod-Kumar-S
Copy link

Hi @Vinod-Kumar-S, thanks, I am glad it's useful for you. Regarding your question, I wrote this 6 years ago, I don't even remember anymore what I created this for back then 😉 I am not sure what you mean about giving examples. The switch case seems to speak for itself by going through the different types that the field can have 🤔 I guess my intention with those comments was to try parsing these values as Double/Boolean to see if that works or creates an exception.

Thank You for the help Benjamin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment