loviji
loviji

Reputation: 13080

JSON returned data formatting

I'm using code below to get JSON data:

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult getBranchViaJson()
    {
       Json(getBranchList(AppSession.BranchID.Value));
    }


    private object getBranchList(int n)
    {

        var mybranchList = from p in getBranchs(n)
                 select new { p.Code, p.Name };
        return mybranchList.ToArray();
    }

Client side retain value : [{"Code":000,"Name":"Milan"}, {"Code":001,"Name":"Istanbul"}, {"Code":002,"Name":"Baku"},]

But I want to get like this:

[{000:"Milan"},{001:"Istanbul"},{002:"Baku"}]

What is the best way to do this?

Upvotes: 0

Views: 162

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

First things first:

[{000:"Milan"},{001:"Istanbul"},{002:"Baku"}]

is invalid JSON. Properties must be quoted like so:

[{"000":"Milan"},{"001":"Istanbul"},{"002":"Baku"}]

In order to achieve this output you could use a Dictionary<string, string> that the JavaScriptSerializer will serialize to the desired output. So simply call the ToDictionary extension method on your model in order to convert it to a dictionary:

Like that:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getBranchViaJson()
{
    var branches = 
        from p in getBranchs(AppSession.BranchID.Value)
        select new { p.Code, p.Name };
    var model = branches.ToDictionary(x => x.Code, x => x.Name);
    return Json(new[] { model }, JsonRequestBehavior.AllowGet);
}

or if you want to keep your private method which returns an object you could make it return a dictionary:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getBranchViaJson()
{
    return Json(getBranchList(AppSession.BranchID.Value), JsonRequestBehavior.AllowGet);
}

private object getBranchList(int n)
{
    var mybranchList = from p in getBranchs(n)
             select new { p.Code, p.Name };
    return new[] { mybranchList.ToDictionary(x => x.Code, x => x.Name) };
}

Notice that I used new[] { model }. That's because otherwise the JavaScriptSerializer won't produce a javascript array as required but a simple javascript object.

Remark: notice that I have added JsonRequestBehavior.AllowGet so that this controller action can be consumed with a GET request which is disabled by default for actions returning JSON responses.

Upvotes: 2

Related Questions