2012-02-28 70 views
2

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

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

回答

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

UPDATE:

,并为那些急切地想测试没有实际存储库:

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。

+0

为什么将'entitiesJson'改为数组可解决任何问题? – gdoron 2012-02-28 23:03:36

+1

@gdoron,因为Json方法使用的'JavaScripSerializer'反映了所提供的模型类型。在询问之前尝试一下代码。我的更新可能会帮助您更好地理解。 – 2012-02-28 23:06:50

+0

嗨达林。这么晚才回复很抱歉。这正是我所期待的。我在我的环境中测试过它,它的功能就像一个魅力一样。我会把这个问题留出几分钟 - 也许别人会想出另一个聪明的解决方案 - 而不是关闭它。我真的很感谢你的努力。谢谢。 – UnclePaul 2012-02-28 23:17:47