返回没有属性名称的Json结果

时间:2012-02-28 22:58:17

标签: .net json asp.net-mvc-3 opensearch

很可能是一个相当微不足道的问题,但我找不到合适的答案。我想返回一个“JsonResult”而实际结果没有任何属性名称。以下是我想要实现的一个小例子:

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

是的,一些非常普通的源代码已经存在,但我怀疑这是否有任何意义。但是,这是:

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

1 个答案:

答案 0 :(得分:5)

你走了:

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

更新:

对于那些没有实际存储库而不耐烦的人:

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

返回:

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

这正是预期的JSON。