Question

Très probablement une question plutôt triviale, mais je ne pouvais tout simplement pas trouver de réponse appropriée. Je veux retourner un "jsonResult" sans que le résultat réel n'ait aucun nom de propriété. Voici un petit exemple de ce que je veux réaliser:

["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"]]

Oui, un code source très ordinaire existe déjà, mais je doute que cela soit de toute pertinence. Cependant, le voici:

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);
}
Était-ce utile?

La solution

Voici:

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);
}

METTRE À JOUR:

Et pour ceux qui sont impatients de tester sans référentiel réel:

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);
}

Retour:

[
    "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"
    ]
]

qui est exactement le JSON attendu.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top