2012-02-28 43 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