返回对象名称为MVC的Json Result

时间:2010-10-28 12:30:58

标签: asp.net-mvc vb.net json

当控制器返回json结果时,对象名称似乎丢失了,我通常不介意,但flexbox jquery插件需要特定格式的json结果。

Flexcombobox预期格式

{"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"}  
 ]} 

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

控制器代码

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结果返回(缩短)

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

期望的结果(缩短)

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

Flexcombobox文档 http://www.fairwaytech.com/flexbox.aspx

2 个答案:

答案 0 :(得分:16)

在C#中,您可以使用匿名对象在其出路时调整JSON结构:

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

<强>更新

来自Dien,这是同一件事的VB语法:

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

答案 1 :(得分:1)

要获得输出JSON的细粒度控制,您可以尝试声明数据契约,如:

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

然后使用DataContractJsonSerializer:

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