Deserializing ReCaptcha JSON with C#

Turning a ReCaptcha request into a strongly-typed C# object on the fly

When requesting a ReCaptcha image, you send out this request:
http://www.google.com/recaptcha/api/challenge?k=your_public_key

You then receive this in return:
var RecaptchaState = {
    site : 'your_public_key',
    challenge : 'returned_challenge_key',
    is_incorrect : false,
    programming_error : '',
    error_message : '',
    server : 'http://www.google.com/recaptcha/api/',
    timeout : 18000
};

document.write('<scr'+'ipt type="text/javascript" 
    s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js">
    </scr'+'ipt>');

Looking at that, you can pull the information you need into this object:
[Serializable]
public class ReCaptchaState
{
    [DataMember]
    public string site { get; set; }

    [DataMember]
    public string challenge { get; set; }

    [DataMember]
    public bool is_correct { get; set; }

    [DataMember]
    public string programming_error { get; set; }

    [DataMember]
    public string error_message { get; set; }

    [DataMember]
    public string server { get; set; }

    [DataMember]
    public int timeout { get; set; }
}

By using this code:
WebClient client = new WebClient();
string ret = client.DownloadString(google_url);
int start = ret.IndexOf('{');
int length = ret.IndexOf('}') - start + 1;
string json = ret.Substring(start, length);

ReCaptchaState state = new JavaScriptSerializer()
    .Deserialize<ReCaptchaState>(json);

Now you have a ReCaptchaState .net object you can use the values from; simple.

Add comment

Loading