JsonConvert.Deserialize JsonResult from MVC action
It 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 successful boolean returned by the JsonResult. I tried to put <Dictionary<string,string>>
right after Deserialize but it didn't settle for the syntax. Used as a type against a variable, etc. Etc.
What is the correct way to do this?
source to share
Assuming you are using .NET 4.0 or higher you can use dynamic
:
dynamic result = JsonConvert.DeserializeObject((string)CheckPlan().Data);
Console.WriteLine(result.success);
If you don't want to dynamic
, you can create your own 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);
source to share
I know this old post, but I had exactly the same problem which I solved this way:
No need to use a 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 in order to dynamic
be able to access the properties of the result object Data
. To do this, add the following line in your AssemblyInfo.cs
MVC project:
// Allow the test project access to internals of MyProject.Web
[assembly: InternalsVisibleTo("MyProject.Test")]
source to share