Reputation: 13
I am working on a Web API 2 Service that needs to accept the data in either json or xml. On the XML side everything works great, on the JSON side whenever there is an array of objects the result is "nothing" for that for that node. Here is an example:
XML:
<AutoShow>
<Title>List of Cars</Title>
<Cars>
<Car>
<Brand>Nissan</Brand>
<Model>Sentra</Model>
</Car>
<Car>
<Brand>Mazda</Brand>
<Model>RX-7</Model>
</Car>
</Cars>
</AutoShow>
JSON:
{
"Title": "List of Cars",
"Cars": {
"Car": [
{
"Brand": "Nissan",
"Model": "Sentra"
},
{
"Brand": "Mazda",
"Model": "RX-7"
}
]
}
}
Model:
Public Class AutoShow
Property Title As String = ""
Property Cars As List(Of Car)
Public Class Car
Property Brand As String = ""
Property Model As String = ""
End Class
End Class
Controller Has:
Public Function PostValue(<FromBody()> ByVal Value As AutoShow)
'Value contains the received data
End Function
When XML is sent in everything is great Title has "List of Cars" and Value.Cars has objects of Car and the Brand and Model both have values.
When JSON is sent Value.Title has "List of Cars" but Value.Cars is "Nothing"
I have tried creating a model that looks like:
Partial Public Class AutoShow
Public Title As String
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Cars As Cars
End Class
<System.Runtime.Serialization.DataContractAttribute()> _
Partial Public Class Cars
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Car() As Car
End Class
<System.Runtime.Serialization.DataContractAttribute()> _
Partial Public Class Car
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Brand As String
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Model As String
End Class
When I use this Model it basically reverses the issue, whereas the JSON works but the XML Value.Cars is "Nothing"
I would appreciate any help as I am new to Web API 2, and have been scouring google on how to resolve this.
Thanks.
Upvotes: 0
Views: 98
Reputation: 13
I found the issue, in using one of those online XML to JSON converters generated the JSON as I have it above. However in order to get it to work the JSON actually needs to be formatted as follows:
{
"Title": "List of Cars",
"Cars": [
{
"Brand": "Nissan",
"Model": "Sentra"
},
{
"Brand": "Mazda",
"Model": "RX-7"
}
]
}
Notice the missing "Car" element. To spend all the hours I did and have it come down to something like this, UGH!
Upvotes: 0