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?

4
  • 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 stackoverflow.com/questions/16441880/how-to-return-json-object Commented Mar 5, 2014 at 13:56
  • 1
    WCF doesn't use Json.Net by default. Either use this 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)) Commented Mar 5, 2014 at 13:58
  • 1
    @Paul I've got it returning a list and it's working. Thanks. Commented Mar 5, 2014 at 14:11
  • I'm also going to try your suggestion @L.B Commented Mar 5, 2014 at 14:11

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.