0

I have created a web service using JSON and REST. What I want to know is how to output contents of a local database using the service?

I am using Visual Studio 2015, ASP.NET Web Forms and LINQ data source.

I think I have to use some c# code as well to get this working but I am not sure.

I have tried different approaches but cannot seem to find the right solution.

I was spending some time on the following but it is not what i am looking for...

http://williamsportwebdeveloper.com/cgi/wp/?p=494

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jordan
  • 97
  • 11

3 Answers3

2

Take a look at the Newtonsoft.Json package available freely on NuGet.

You can use the Newtonsoft.Json.JsonConvert.SerializeObject(object) method to return a JSON representation of the object parameter provided as a string.
This can be returned to the user of the web service as is.

Since you're using LINQ, I'm assuming you've got your data structure set up including classes, so you can make a connection to the database, process the results to create your objects, and finally use the SerializeObject(object) method to serialize the root object as JSON to be returned to the user of the web service.

Nathangrad
  • 1,426
  • 10
  • 25
2

See if this help:

http://andre-pedroso.blogspot.pt/2013/03/endpoint-on-aspnet-page-returning-json.html

It isn´t from an IQueryable but from a DataTable, but the return type is what you looking for.

[System.Web.Services.WebMethod]
public static string GetData()
{
    DataTable dt = GetDataTable();

    return BuildJSONFromDT(dt);
}

private static string BuildJSONFromDT(DataTable dt)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();

    List<object> resultMain = new List<object>();

    foreach (DataRow row in dt.Rows)
    {
        Dictionary<string, object> result = new Dictionary<string, object>();
        foreach (DataColumn column in dt.Columns)
        {
            result.Add(column.ColumnName, "" + row[column.ColumnName]);
        }

        resultMain.Add(result);
    }

    return serializer.Serialize(resultMain);
}

Cheers!

André Pedroso
  • 1,574
  • 1
  • 17
  • 16
2

If I have understood correctly, You want to output LINQ data to JSON.

  1. First convert LINQ to datatable using code presented here

  2. Convert DataTable to JSON using the method detailed here Also a similar question on DataTable to JSON is answered here

Community
  • 1
  • 1
udaya kumar
  • 169
  • 8