如何将JsonResult对象作为字符串获取,以便我可以修改它?

时间:2008-11-24 02:17:12

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

我正在使用FlexiGrid jQuery插件,我需要从我的MVC应用程序中获取一个JSON对象,如果FlexiGrid仅使用该对象就足够简单但我需要在响应字符串中添加一些项目以使其工作适当地使用FlexiGrid。

所以这是我控制器代码的一部分:

If Request.QueryString("json") IsNot Nothing Then
    Dim data As New StringBuilder()
    data.Append("page: " & pageIndex & "," & vbCrLf)
    data.Append("total: " & ViewData.TotalCount & "," & vbCrLf)
    data.Append("rows: ")
    data.Append(Json(objCustomerList))

    Return Content(data.ToString())
End If

不幸的是,在上面的代码中Json(objCustomerList)返回'System.Web.MVV.JsonResult'而不是所需的JSON字符串数据。我也试过Json(objCustomerList).ToString()只是为了看看会发生什么,再次发生同样的事情。

有什么想法吗?

4 个答案:

答案 0 :(得分:15)

ASP.NET MVC中的

Json()方法只是通过JsonResult类使用JavaScriptSerializer类。如果您想使用JSON将objCustomerList对象序列化为字符串,则可以自己使用它。

我的建议是采取略微不同的方法。

  • 创建一个模型,表示您尝试创建的JavaScript对象的.NET等效项。可能是具有Page,Total,Rows和CustomerList属性的FlexiGridModel对象。
  • 然后当您将FlexiGridModel传递给Json()时,它就可以正常工作,无需使用StringBuilder构建JSON字符串。

如果您只想让代码正常工作,则会有一个override on JavaScriptSerializer.Serialize()将对象序列化,StringBuilder将结果附加到其中。这应该是你正在寻找的。

一些相关链接:

答案 1 :(得分:10)

你也可以这样做:

JsonResult json = ... ;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string yourJsonResult = serializer.Serialize(json.Data);

简单:D

编辑:代码高照明

答案 2 :(得分:2)

我最后修改了Code Project示例:

Imports System.Web.Script.Serialization
Imports System.Reflection

Public Class FlexiGrid

    Public Class FlexigridRow
        Public id As String
        Public cell As New List(Of String)()
    End Class

    Public Class FlexigridObject
        Public page As Integer
        Public total As Integer
        Public rows As New List(Of FlexigridRow)()
    End Class

    Public Shared Function GetFlexiGridJSON(ByVal page As Integer, ByVal total As Integer, ByVal o As Object) As String

        Dim js As New JavaScriptSerializer
        Dim flexiGrid As New FlexigridObject
        Dim i As Integer = 0
        flexiGrid.page = page
        flexiGrid.total = total

        For Each c In o
            Dim r As New FlexigridRow()
            r.id = i
            r.cell = GetPropertyList(c)
            flexiGrid.rows.Add(r)
            i += i
        Next

        Return js.Serialize(flexiGrid)
    End Function

    Private Shared Function GetPropertyList(ByVal obj As Object) As List(Of String)

        Dim propertyList As New List(Of String)()

        Dim type As Type = obj.[GetType]()
        Dim properties As PropertyInfo() = type.GetProperties(BindingFlags.Instance Or BindingFlags.[Public])
        For Each [property] As PropertyInfo In properties
            Dim o As Object = [property].GetValue(obj, Nothing)
            propertyList.Add(If(o Is Nothing, "", o.ToString()))
        Next

        Return propertyList

    End Function

End Class

现在在我的控制器中我只是打电话:

Return Content(GetFlexiGridJSON(pageIndex, TotalCount, objCustomerList))

只要我传递的对象是一个对象列表就可以完美地运行。

答案 3 :(得分:0)

本文介绍如何让Flexigrid逐步使用MVC:

ASP.NET MVC Flexigrid sample