Reputation: 612
Should be simple! How can I accomplish the following?
JsonResult result = JsonConvert.Deserialize(CheckPlan());
Where CheckPlan() returns this:
return Json(new { success = success }, JsonRequestBehavior.AllowGet);
I am unable to parse the success boolean value returned by the JsonResult. I have tried to put <Dictionary<string,string>>
right after Deserialize but it was balking on the syntax. Used like a type vs. a variable, etc.,etc.
What is the correct way to do this?
Upvotes: 3
Views: 8589
Reputation: 820
I know it's an old post but I had exactly the same problem, which I solved as follows:
No need to use the deserializer!
dynamic result = CheckPlan().Data;
Console.WriteLine(result.success);
In my case I was writing a unit test for an MVC controller method. Since the test methods are in their own project I had to give them access to the internals of the MVC project so that the dynamic
could access the properties of the result's Data
object. To do this add the following line to AssemblyInfo.cs
in the MVC project:
// Allow the test project access to internals of MyProject.Web
[assembly: InternalsVisibleTo("MyProject.Test")]
Upvotes: 5
Reputation: 149646
Assuming you're using .NET 4.0 or above, you can use dynamic
:
dynamic result = JsonConvert.DeserializeObject((string)CheckPlan().Data);
Console.WriteLine(result.success);
If you dont want dynamic
, you can create a custom class with a success
boolean property:
public class Foo
{
[JsonProperty("success")]
public bool Success { get; set; }
}
And then:
Foo result = JsonConvert.DeserializeObject<Foo>((string)CheckPlan().Data);
Console.WriteLine(result.Success);
Upvotes: 2