如何将VB.NET中的List序列化为JSON

时间:2012-06-03 07:03:51

标签: asp.net asp.net-mvc vb.net web-services

我有以下代码将邮件列表转换为json

Public Class MessageService
    <OperationContract()> _
    Public Function GetMessage(Id As Integer) As String



        Dim msg As New Message()
        Dim stream As New MemoryStream()
        Dim serializer As New DataContractJsonSerializer(GetType(NewMessage))

        Dim dtMessages = msg.getUnreadMessages("3A3458")

        Dim list As New ArrayList

        Dim m As New NewMessage()
        m.Id = 1
        m.Text = "mmsg"
        list.Add(m)
        list.Add(m)
        serializer.WriteObject(stream, list)

        stream.Position = 0
        Dim streamReader As New StreamReader(stream)
        Return streamReader.ReadToEnd()
    End Function
End Class

但是我收到了以下错误:

    The server was unable to process the request due to an internal error. 
 For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, 
or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

1 个答案:

答案 0 :(得分:2)

下面:

Dim serializer As New DataContractJsonSerializer(GetType(NewMessage))

您向序列化程序指明您要序列化NewMessage实例。

在这里:

serializer.WriteObject(stream, list)
你正在传递Arraylist。这显然是模棱两可的。我建议你修改你的方法,以便它直接返回一个强类型的集合,并将JSON序列化保留给绑定,而不是在数据协定中编写管道代码:

Public Class MessageService
    <OperationContract()> _
    Public Function GetMessage(Id As Integer) As List(Of NewMessage)
        Dim list As New List(Of NewMessage)
        Dim m As New NewMessage()
        m.Id = 1
        m.Text = "mmsg"
        list.Add(m)

        Return list
    End Function
End Class