Return Json result with MVC object name

When the json result is returned by the controller, the name of the object seems to be missing, I usually don't mind, but the jQuery flexbox plugin requires json to cast to a specific format.

expected Flexcombobox format

{"results":[ {"id":"1","name":"Ant"}, {"id":"2","name":"Bear"}, {"id":"3","name":"Cat"}, {"id":"4","name":"Dog"}, {"id":"5","name":"Elephant"}, {"id":"6","name":"Fox"}, {"id":"7","name":"Guinea Pig"}, {"id":"8","name":"Horse"}, {"id":"9","name":"Iguana"}, {"id":"10","name":"Jaguar"} ]} 

Class

 Public Class FlexboxResult Private _id As String Public Property Id() As String Get Return _id End Get Set(ByVal value As String) _id = value End Set End Property Private _name As String Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property End Class 

Controller code

 Function PartYearsList() As JsonResult Dim yearSelectList As List(Of FlexboxResult) = New List(Of FlexboxResult) For index As Integer = DateTime.Now.Year To 1955 Step -1 yearSelectList.Add(New FlexboxResult() With {.Id = index, .Name = index}) Next Return Me.Json(yearSelectList.ToArray(), JsonRequestBehavior.AllowGet) End Function 

Json result returned (shortened)

 [{"Id":"2010","Name":"2010"},{"Id":"2009","Name":"2009"},{"Id":"2008","Name":"2008"}] 

Desired Result (Reduced)

 {"results": [{"Id":"2010","Name":"2010"},{"Id":"2009","Name":"2009"},{"Id":"2008","Name":"2008"}]} 

Flexcombobox Documentation http://www.fairwaytech.com/flexbox.aspx

+4
source share
2 answers

In C #, you can use an anonymous object to configure the JSON structure in the output:

 // The ToArray() probably isn't necessary. Collections like List<T> are treated // as JavaScript arrays when JavaScriptSerializer turns them into JSON. return Json(new { results = yearSelectList}); 

Update:

From Dien, this is the VB syntax for the same:

 Return Json(New With {Key .results = yearSelectList}, JsonRequestBehavior.AllowGet) 
+16
source

To get precise grain control of the output JSON, you can try declaring a data contract, for example:

 [DataContract] public class MyResultListContract { [DataMember] public List<MyResultContract> results { get; set; } } [DataContract] public class MyResultContract { [DataMember] public string Id {get; set;} [DataMember] public string Name {get; set;} } 

and then using DataContractJsonSerializer:

 var myResults = ... var serialiser = new DataContractJsonSerializer(typeof(MyResultListContract)); var jsonString = serialiser.WriteAsString(myResults); 
+1
source

All Articles