3

I have a REST service which returns a json serialized DataTable.

When I make a request to the service I get no data ("No data receieved" from chrome), but when I change the return type to string and return a string which is the serialized DataTable, everything works fine (except I have to parse the Json string).

//Doesn't Work
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "data")]
public DataTable LoadData2() {

    return JsonQueryDatabase2(VCAPSProduction);
}

.

// Works, but returns a json string
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "data")]
public string LoadData2() {

    return JsonConvert.SerializeObject(JsonQueryDatabase2(connString));
}

How can I get my service to return a Json object using a DataTable?

kschieck
  • 1,407
  • 2
  • 16
  • 29
  • 1
    This is because the 'object' that you are serialising is a datatable, hence you get a datatable at the other end, populate a list of objects instead and serialise that, is generally the convention. Have a read of http://stackoverflow.com/questions/16441880/how-to-return-json-object – Paul Zahra Mar 05 '14 at 13:56
  • 1
    WCF doesn't use Json.Net by default. Either use [this](http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx) to use Json.Net as the serialiazer, or return `System.ServiceModel.Channels.Message` And fill it with Json.Net as you do now. (`return WebOperationContext.Current.CreateTextResponse(serializeHere)`) – L.B Mar 05 '14 at 13:58
  • 1
    @Paul I've got it returning a list and it's working. Thanks. – kschieck Mar 05 '14 at 14:11
  • I'm also going to try your suggestion @L.B – kschieck Mar 05 '14 at 14:11

1 Answers1

2

I ended up going with L.B's suggestion.

using Newtonsoft.Json; // JsonConvert.SerializeObject

...

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "data?limit={limit}")]
public System.ServiceModel.Channels.Message LoadData_Limited(int limit) {

    if (limit <= 0) { return null; }

    string query = ...;

    try {

        ...

        //Return data from query
        DataTable dt = QueryDatabase(connString, query, parameters);
        string serialized = JsonConvert.SerializeObject(dt);
        return WebOperationContext.Current.CreateTextResponse(serialized);

    } catch {
        return null;
    }
}
Community
  • 1
  • 1
kschieck
  • 1,407
  • 2
  • 16
  • 29