Reputation: 297
Please check the controller bellow. I have to process the Json response inside this controller. My goal is to grab "success" value true or false. How can i access that value from following json response? I already tried to use JsSerialializer but no luck. Please check pictures for better understanding. Thanks in advance.
View Model:
public class GoogleRecaptcha
{
public bool success { get; set; }
public DateTime challenge_ts { get; set; }
public string hostname { get; set; }
}
public ActionResult DownloadProcess()
{
using (BlexzWebDbEntities db = new BlexzWebDbEntities())
{
//Validate Google recaptcha below
var Response = Request["g-recaptcha-response"];
string SecretKey = "6Lghu-MJoniMPXVf";
//var client = new WebClient();
var client = new RestClient("https://www.google.com/recaptcha/api/siteverify");
var request = new RestRequest(Method.POST);
request.Method = Method.POST;
request.Parameters.Clear();
request.AddParameter("secret", SecretKey);
request.AddParameter("response", Response);
var ResultFromGoogle = client.Execute(request).Content;
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var r = jsSerializer.DeserializeObject(ResultFromGoogle);
return View();
}
}
Upvotes: 0
Views: 72
Reputation: 31312
There are multiple ways to do what you want:
1. Using JavaScriptSerializer with strongly typed model:
public class ResultFromGoogle
{
public bool Success { get; set; }
public DateTime Challenge_ts { get; set; }
public string Hostname { get; set; }
}
ResultFromGoogle results = jsSerializer.Deserialize<ResultFromGoogle>(ResultFromGoogle);
var successValue = results.Success;
2. Using JavaScriptSerializer without strongly typed model:
var props = (Dictionary<string, object>)jsSerializer.DeserializeObject(ResultFromGoogle);
var successValue = props["success"];
3. Using JSON.Net with strongly typed model:
var results = JsonConvert.DeserializeObject<ResultFromGoogle>();
var successValue = results.Success;
4. Using JSON.Net without strongly typed model:
var successValue = JObject.Parse(ResultFromGoogle).GetValue("success");
Overall, I suggest using strongly-typed model, because it provides conversion to required type (e.g. bool
for success
property and DateTime
for challenge_ts
). It's also more convenient if you need to access other fields of the response.
Json.Net in its turn is much more flexible than JavaScriptSerializer
. You need to install Json.Net NuGet to use options #3 and #4.
Upvotes: 1