Json serialization in asp.net mvc c #
public ActionResult About()
{
List listStores = new List();
listStores = this.GetResults("param");
return Json(listStores, "Stores", JsonRequestBehavior.AllowGet);
}
Using the above code, I can get the following output:
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
"email":"abc@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
how can i get the result in below format? We need shops at the beginning of the result.
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
"email":"abc@ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"
}} ] }
+3
source to share
1 answer
Try
return Json(new { stores = listStores }, JsonRequestBehavior.AllowGet);
In the above statement, you create a new object with a property named Stores, which is then populated with an array of items from the list.
You can also use a class, something defined like this:
[DataContract]
public class StoreListJsonDTO
{
[DataMember(Name = "stores")]
public List Stores { get; set; }
public StoreListJsonDTO(List storeList)
{
this.Stores = storeList;
}
}
Then, in your code, you must:
var result = new StoreListJsonDTO(listStores);
return Json(result, JsonRequestBehavior.AllowGet);
+8
source to share