Question

Very likely a rather trivial question, but I simply couldn't find an appropriate answer. I want to return a "JsonResult" without the actual result having ANY property names whatsoever. Here is a little example of what I want to achieve:

["xbox", 
["Xbox 360", "Xbox cheats", "Xbox 360 games"], 
["The official Xbox website from Microsoft", "Codes and walkthroughs", "Games and accessories"],
["http://www.xbox.com","http://www.example.com/xboxcheatcodes.aspx", "http://www.example.com/games"]]

Yes, some very ordinary source code already exists, but I doubt this is of any relevance. However, here it is:

public JsonResult OpensearchJson(string search)
{
    /* returns some domain specific IEnumerable<> of a certain class */
    var entites = DoSomeSearching(search); 

    var names = entities.Select(m => new { m.Name });
    var description = entities.Select(m => new { m.Description });
    var urls = entities.Select(m => new { m.Url });
    var entitiesJson = new { search, names, description, urls };
    return Json(entitiesJson, JsonRequestBehavior.AllowGet);
}
Was it helpful?

Solution

Here you go:

public ActionResult OpensearchJson(string search)
{
    /* returns some domain specific IEnumerable<> of a certain class */
    var entities = DoSomeSearching(search); 

    var names = entities.Select(m => m.Name);
    var description = entities.Select(m => m.Description);
    var urls = entities.Select(m => m.Url);
    var entitiesJson = new object[] { search, names, description, urls };
    return Json(entitiesJson, JsonRequestBehavior.AllowGet);
}

UPDATE:

and for those that are impatient to test without an actual repository:

public ActionResult OpensearchJson(string search)
{
    var entities = new[]
    {
        new { Name = "Xbox 360", Description = "The official Xbox website from Microsoft", Url = "http://www.xbox.com" },
        new { Name = "Xbox cheats", Description = "Codes and walkthroughs", Url = "http://www.example.com/xboxcheatcodes.aspx" },
        new { Name = "Xbox 360 games", Description = "Games and accessories", Url = "http://www.example.com/games" },
    };

    var names = entities.Select(m => m.Name);
    var description = entities.Select(m => m.Description);
    var urls = entities.Select(m => m.Url);
    var entitiesJson = new object[] { search, names, description, urls };
    return Json(entitiesJson, JsonRequestBehavior.AllowGet);
}

returns:

[
    "xbox",
    [
        "Xbox 360",
        "Xbox cheats",
        "Xbox 360 games"
    ],
    [
        "The official Xbox website from Microsoft",
        "Codes and walkthroughs",
        "Games and accessories"
    ],
    [
        "http://www.xbox.com",
        "http://www.example.com/xboxcheatcodes.aspx",
        "http://www.example.com/games"
    ]
]

which is exactly the expected JSON.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top