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

+1

@gdoronです。Jsonメソッドで使用される 'JavaScripSerializer'が、提供されたモデルタイプで'反映される 'ためです。質問する前にコードを試してください。私の更新は、より良い理解に役立つかもしれません。 –

+0

こんにちはダーリン。返事が遅れて申し訳ありません。これはまさに私が探していたものです。私は自分の環境でそれをテストし、チャーミーのように動作します。私はこの質問を数分開いたままにしておきます。誰か他の巧妙な解決策が浮かび上がってくるかもしれません。私は本当にあなたの努力に感謝します。ありがとうございました。 – UnclePaul

関連する問題