VB.Net将匿名类型序列化为xml

时间:2010-10-07 23:19:21

标签: vb.net .net-4.0 xml-serialization anonymous-types

在MVC中,我可以执行以下操作,将具有匿名类型的对象序列化为JSON ...

    Public Function GetStateList() As JsonResult
        Dim MyObject = New With {.Id = 1, .Property = "SomeValue"}
        Return Me.Json(MyObject)
    End Function

会返回类似的内容;

{
    "Id": 1,
    "Property"SomeValue",
}

我想完全相同但输出xml。我找不到一个等效的方法。有人请指出我正确的方向吗?

非常感谢

2 个答案:

答案 0 :(得分:1)

简短的回答是你不能,看到这个post。我建议您创建一个具体类型来表示匿名输出的结构,然后使用普通的XML序列化技术,就像我在下面提供的示例一样。

以下是如何使用它的基本示例(抱歉是C#语法):

using (MemoryStream memStream = new MemoryStream())
{
    System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); 
    // read and convert to byte array
    XmlSerializer serializer = new XmlSerializer( <<yourObject>>.GetType() ); 
    serializer.Serialize( memStream, <<yourObject>>)); 
    string output = utf8.GetString( memStream.ToArray() );
}

答案 1 :(得分:1)

根据詹姆斯的回答,没有本地的做法。使用Reflector,我检查了System.Web.MVC.dll,并了解了MVC是如何做到的。代码的核心如下。

Private Sub SerializeCustomObject(ByVal o As Object, ByVal sb As StringBuilder, ByVal depth As Integer, ByVal objectsInUse As Hashtable, ByVal serializationFormat As SerializationFormat)
    Dim flag As Boolean = True
    Dim type As Type = o.GetType
    sb.Append("{"c)
    If (Not Me.TypeResolver Is Nothing) Then
        Dim str As String = Me.TypeResolver.ResolveTypeId(type)
        If (Not str Is Nothing) Then
            JavaScriptSerializer.SerializeString("__type", sb)
            sb.Append(":"c)
            Me.SerializeValue(str, sb, depth, objectsInUse, serializationFormat)
            flag = False
        End If
    End If
    Dim info As FieldInfo
    For Each info In type.GetFields((BindingFlags.Public Or BindingFlags.Instance))
        If Not info.IsDefined(GetType(ScriptIgnoreAttribute), True) Then
            If Not flag Then
                sb.Append(","c)
            End If
            JavaScriptSerializer.SerializeString(info.Name, sb)
            sb.Append(":"c)
            Me.SerializeValue(info.GetValue(o), sb, depth, objectsInUse, serializationFormat)
            flag = False
        End If
    Next
    Dim info2 As PropertyInfo
    For Each info2 In type.GetProperties((BindingFlags.GetProperty Or (BindingFlags.Public Or BindingFlags.Instance)))
        If Not info2.IsDefined(GetType(ScriptIgnoreAttribute), True) Then
            Dim getMethod As MethodInfo = info2.GetGetMethod
            If ((Not getMethod Is Nothing) AndAlso (getMethod.GetParameters.Length <= 0)) Then
                If Not flag Then
                    sb.Append(","c)
                End If
                JavaScriptSerializer.SerializeString(info2.Name, sb)
                sb.Append(":"c)
                Me.SerializeValue(getMethod.Invoke(o, Nothing), sb, depth, objectsInUse, serializationFormat)
                flag = False
            End If
        End If
    Next
    sb.Append("}"c)
End Sub

这是相当不言自明的,很容易转换。