Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonConvert.Deserialize JsonResult from MVC Action

Tags:

c#

json.net

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?

like image 807
jallen Avatar asked Mar 04 '26 06:03

jallen


2 Answers

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")]
like image 154
AndyS Avatar answered Mar 05 '26 19:03

AndyS


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);
like image 34
Yuval Itzchakov Avatar answered Mar 05 '26 20:03

Yuval Itzchakov