I would like to validate the JSON being passed in, currently the method is not parsing the JSON and bad json will go on to break everything, and I imagine security exploits can be built into a bad JSON string as well.
JsonParser parser = new JsonParser();
JsonObject bodyvar = parser.parse(params.get("body")).getAsJsonObject();
How can I check validate the JSON? (ideally I can get a boolean value or a 1 or 0 returned, so I can construct this method conditionally. Or if there is a try/catch that comes with the JSONParser for validation, that would be cool too)
edit: using GSON library (and I’ll be looking at the GSON reference while I wait for answers here)
Without knowing which library you’re using, it’s hard to be specific, but most parsing libraries will throw an exception if the JSON was mal-formed, so you shouldn’t have to worry about the JSON going on to break anything else. If you simply throw a try/catch block around the call to
parser.parse(), you’ll probably be in pretty good shape.And JSON can’t really hurt anything server-side, so unless you’re planning to pass this JSON string from one user’s browser to another, you won’t have any security vulnerabilities from it anyway.
Edit
Since you’re using gson, a
JsonSyntaxExceptionwill be thrown if the JSON is mal-formed. You can catch that exception specifically if there’s something you want to do differently in that case.