Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebAPI Putting Underscores on Returned Element Names in XML and JSON

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!

like image 399
Rich Miller Avatar asked Dec 09 '22 22:12

Rich Miller


2 Answers

Remove <Serializable()> before Class, then results will not contain "_".

like image 111
Guanyc Avatar answered May 27 '23 04:05

Guanyc


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.

like image 42
Darin Dimitrov Avatar answered May 27 '23 04:05

Darin Dimitrov