fl3rgle fl3rgle - 1 month ago 11
Vb.net Question

ASP.NET Web API return ArrayList as JSON

I'm new to web API, and all the examples are in C# which doesn't help, as such I've hit a roadblock early on. I'm returning data from SQL, putting it an object array list, and then trying to return it so it could be read by a JSON client.

This is my default GET on my controller:

Function Index() As IEnumerable(Of String)
Dim Sites As New ArrayList
Dim dt As DataTable = DataLayer.ExecuteNoParamStoredProcedure("stored_proc", "connection_string")

For Each r As DataRow In dt.Rows()
Sites.Add(New SiteDetails(r("SiteName"),r("SiteId")))
Next

Return Sites
End Function


And here is my SiteDetails class:

Public Class SiteDetails
Public site As String
Public siteid As String

Public Sub New(sitename As String, id As String)
site = sitename
siteid = id
End Sub
End Class


Questions: How to I make it output the data on the page in a format that isn't either an error or just the object name? Is there a better way to do what I'm doing?

Joe

EDIT just to comment, the above doesn't work from the off, because it can't the return type (IEnumerable(Of String)) doesn't allow an arraylist to be returned, this is the bulk of my issue.

Answer

In your sample, you return an IEnumerable(Of String). Therefore, when returning the result of your action method, all objects are converted to a string by calling the ToString method (I suspect you have OPTION STRING turned OFF in your project); in your case, the default implementation of ToString is used. This implementation returns the name of the type.

In order to return the data, I'd change the code as follows:

  • If you want to return all object properties, change the signature of your action method to Function Index() As IEnumerable(Of SiteDetails)
  • If you want to return some strings, leave the signature of your action method as it is, but override the ToString method of the SiteDetails class so that the required data are formatted as a string correctly.

In addition, I'd propose not to use the ArrayList class anymore; there is a strongly typed List(Of T) class (in your case List(Of SiteDetails) if you want to return the SiteDetails objects or List(Of String) if you want to return strings).


Also, make sure that you are using a Web API controller. These controllers are derived from the ApiController class (as opposed to a MVC controller that looks roughly the same, but is derived from System.Web.Mvc.Controller).

Comments