2010-10-07 126 views
2

在MVC我可以做一些類似下面的序列化對象與匿名類型JSON ...VB.Net序列化匿名類型的XML

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

這將返回類似;

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

我想要做的完全一樣,但輸出xml。我一直無法找到同等的方法。請有人指點我正確的方向?

非常感謝

回答

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 

這是相當不言自明的,很容易轉換。

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