3
public ActionResult About()
{
List listStores = new List();
listStores = this.GetResults(“param”);
return Json(listStores, “Stores”, JsonRequestBehavior.AllowGet);
}

Using the above code I am able to get the below result :

[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
  "email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}},
 {"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}},

how would I able to get the result in below format? Would need stores at the beginning of the result.

{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
     "email":"[email protected]",
     "geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
     "email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"
}} ] }
1
  • Is there any particular reason why you need stores as the first member of the object? Commented Mar 7, 2012 at 2:37

1 Answer 1

8

Try

return Json(new { stores = listStores }, JsonRequestBehavior.AllowGet);

In the above statement, you're creating a new object with a property named "stores", which is then populated with the array of items from the list.

You could also use a class, something defined like so:

[DataContract]
public class StoreListJsonDTO
{
    [DataMember(Name = "stores")]
    public List Stores { get; set; }

    public StoreListJsonDTO(List storeList)
    {
        this.Stores = storeList;
    }
}

Then in your code, you'd do:

var result = new StoreListJsonDTO(listStores);
return Json(result, JsonRequestBehavior.AllowGet);
Sign up to request clarification or add additional context in comments.

8 Comments

lets say i want to change the name of the "stores" to some thing else like serialization attributes.
I want to change the "Stores" to some other name in the future. Is there a way that I can have it as attribute please? like DataContract<name>
Well, yes, you could create a class that has a property that holds the list, and decorate that property with the necessary attributes ([DataContract] on the class, then [DataMember(Name = "Whatever_you_want")] on the property itself. I just gave you an anonymous object example for the sake of brevity.
[DataMember(Name = "stores")] not working when I return it as asp.net mvc action result
Ahhh, by default MVC3 uses JavascriptSerializer. To use the DataContract / DataMember attributes, you'll need to force it to use the DataContractJsonSerializer as noted here: stackoverflow.com/questions/1302946/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.