Last active
April 14, 2022 09:10
-
-
Save benjaminaaron/204415077e1c7efe45b20b323c8a83d9 to your computer and use it in GitHub Desktop.
validate json by reflection before using gson
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 = "foo"; | |
private double dbl = 0.8; | |
private boolean bool = false; | |
} |
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.*; | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank You for the help Benjamin.