2

My controller is returning Json result of List

Public ActionResult Index([DataSourceRequest] DataSourceRequest request)
{
       var list = new List<Product>();
       Json(list.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

Below is the code of my Unit Test method,in which i am calling above method:

//Act
var actualResult = _Controller.Index(request) as JsonResult;
var data = actualResult.Data;

And now i want to covert this data object to its original type means List.

I tried like below :-

var result = ser.Deserialize<List<Product>>(ser.Serialize(actualResult.Data));

But i am not getting my original data by this.Can anyone help me out,how we can covert jsonresult.data output to its original type ?

Pawan
  • 2,150
  • 11
  • 45
  • 73

2 Answers2

1

Your Index action is returning a DataSourceResult that contains your List, and not a simple List (Json(list.ToDataSourceResult(request)). You first need to deserialize the result as a DataSourceResult, or as a JsonObject, and then select the List of Products.

In the DataSourceResult (KendoUI object) the list is in the Data Property:

System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = ser.Deserialize<Kendo.Mvc.UI.DataSourceResult>(ser.Serialize(actualResult.Data));
var list = result.Data; //as an ArrayList

Using Javascript Object:

System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = (Dictionary<string, object>)ser.DeserializeObject(ser.Serialize(actualResult.Data));
var list = ser.Deserialize<List<Product>>(ser.Serialize(result["Data"]));

Using Newtonsoft Json:

var result = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(JsonConvert.SerializeObject(actualResult.Data));
var list = JsonConvert.DeserializeObject<List<Product>>(result.SelectToken("Data").ToString());
Stefano Castriotta
  • 2,823
  • 3
  • 16
  • 26
0

Are you using Telerik Kendo? If so, the DataSourceResult has its own Cast() method to do this for you. This should do the trick:

var data = actualResult.Data.Cast<Product>().ToList();
nhershy
  • 643
  • 1
  • 6
  • 20