Reputation: 810
I am doing some simple testing of the new ASP.NET Web API, and I am experiencing the following problem when returning a serializable class or collection from my action method.
My class looks like this:
<Serializable()>
Public Class Test
<XmlElement(ElementName:="Name")>
Public Property Name() As String = String.Empty
<XmlElement(ElementName:="ID")>
Public Property ID() As String = String.Empty
<XmlElement(ElementName:="ClassID")>
Public Property ClassID() As String = String.Empty
End Class
My test action method to retrieve a single Test looks like this:
Public Function GetTest(ByVal id As String) As Test
Dim newTest As Test = new Test() With {.ID = id, .Name = "My Test", .ClassID = System.Guid.NewGuid().ToString()}
return newTest
End Function
When I view the results in the browser or in Fiddler as either XML or JSON, the property names of the returned Test class have had unserscores prepended to them, like so:
<Test>
<_ClassID>88bb191d-414c-45a4-8213-37f96c41a12d</_ClassID>
<_ID>ed853792-b7eb-4378-830b-1db611e12ec9</_ID>
<_Name>Another Test</_Name>
</Test>
How do I get rid of the unwanted underscores on the element/property names?
Thanks!
Upvotes: 4
Views: 2267
Reputation: 46
I had a similar experience with the prepended underscores in json and I did not have the class marked with the Serializable attribute. In my case the fix was:
Imports Newtonsoft.Json
<JsonObject>
Public Class MyObject
...
Upvotes: 0
Reputation: 81
Remove <Serializable()>
before Class, then results will not contain "_".
Upvotes: 8
Reputation: 1039130
You could use the DataMember attribute:
Public Class Test
<DataMember(Name:="Name")>
Public Property Name() As String = String.Empty
<DataMember(Name:="ID")>
Public Property ID() As String = String.Empty
<DataMember(Name:="ClassID")>
Public Property ClassID() As String = String.Empty
End Class
After further investigation it seems that if you do the same thing in C#, no underscores are added and no need to use DataMember. It just works. So I guess this oughta be some VB.NET thingy thing.
Upvotes: 6