Thursday, July 30, 2015

Deserialize any randomly-shaped JSON object to a dynamic type in C# with JavaScriptSerializer and then pull properties off of it.

JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<dynamic>(reader.ReadToEnd());
bool isVerified = jsonObject["success"];

 
 

This is an example directly from here which is some mostly working code for interfacing with Google reCAPTCHA (reCAPTCHA is a spiffier version of CAPTCHA that is harder for bots to beat and there is a C# library for it). If you want to use this code please note that the line for making a new WebRequest is crafted wrong and there is a better example of how to do so here. The whole thing should look like:

  1. String recaptcha = Request.Form["g-recaptcha-response"];
    string x = "secret=" +
    YOURKEY + "&response=" + recaptcha;
    WebRequest webRequest = WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?" + x);
    webRequest.Method = "GET";
    WebResponse webResponse = webRequest.GetResponse();
    Stream stream = webResponse.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    The YOURKEY above variable is either a public or private key that one gets from Google, and one will get both. I was only exposed to this in helping a friend with code last night and I only see some of what's going on here.
  2. Next comes the three lines of code at the top of the blog posting. The thing you really want is the isVerified true/false value which will be false if the reCAPTCHA isn't undertaken successfully and true if the user is not a robot.
  3. The next three lines of code do a .Close(); on reader, stream, and webResponse. I guess I would have used a using statement if I wrote this, but of course, I didn't. I had to steal code from someone else who was competent. :P

No comments:

Post a Comment