2

I have a method which is returning Json Result Like :

return Json(new { status = "error", message = "The organization cannot be deleted because contains transmitters!" });

Now I want to test with status and Message I have tried with this

var result = Controller.DeleteOrganization(2) as JsonResult;
Assert.AreEqual("error", result.Data.message);

I am getting Error:

object does not contain a definition for message

How can I resolve this Issue?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Sivamohan Reddy
  • 436
  • 1
  • 8
  • 26
  • 1
    the Data is of type `object` and would not be exposing the property. Try assigning the Data property to a `dynamic` variable and then try accessing the property. if that does not work then I gave an answer [here](http://stackoverflow.com/a/38446754/5233410) and [here](http://stackoverflow.com/a/38552771/5233410) that you can adapt to your problem. – Nkosi Apr 27 '17 at 09:39
  • yes, you are right. Thank you :) – Sivamohan Reddy Apr 27 '17 at 09:45

2 Answers2

2

The Data is of type object and would not be exposing the property. Try assigning the Data property to a dynamic variable and then try accessing the property.

var result = Controller.DeleteOrganization(2) as JsonResult;
var data = JsonConvert.SerializeObject(result.Data);
var deserializedData = JsonConvert.DeserializeObject<dynamic>(data);
Assert.AreEqual("error", deserializedData.status);

If that does not work then I gave an answer here and here that you can adapt to your problem.

Community
  • 1
  • 1
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0
  1. Use json2csharp.com convert JSON to C#
  2. Create a class file put the code
  3. Add the Newtonsoft.Json library to your project using the Nuget Package Manager
  4. Convert the JSON

    RootObject r = JsonConvert.DeserializeObject(json);

  • Thanks for your Reply But, I have tried with JavaScriptSerializer serializer = new JavaScriptSerializer(); var jsonResult =serializer.Deserialize(result.Data.ToString()); as well – Sivamohan Reddy Apr 27 '17 at 05:13
  • 2
    JavascriptSerializer is deprecated, please use NewtonSoft Json for better performance and other reasons. – loneshark99 Apr 27 '17 at 05:19