按照詹姆斯的答案有這樣做的沒有原生的方式。使用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
這是相當不言自明的,很容易轉換。