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?

2
  • 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 and here that you can adapt to your problem. Commented Apr 27, 2017 at 9:39
  • yes, you are right. Thank you :) Commented Apr 27, 2017 at 9:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

Thanks for your Reply But, I have tried with JavaScriptSerializer serializer = new JavaScriptSerializer(); var jsonResult =serializer.Deserialize<Result>(result.Data.ToString()); as well
JavascriptSerializer is deprecated, please use NewtonSoft Json for better performance and other reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.