0

So i have httpget request, that should return a datatable from my database. I convert my datatable into EnumerableRowCollection ,then serialize it into json string (using json.net):

public string GetResult(DataTable dt)
{
 EnumerableRowCollection Result = from row in dt.AsEnumerable()
                                 select new
                                 {
                                     account = (string)row["ACCOUNT_ID"],
                                     balance = (decimal)row["BALANCE"]
                                 }; 
 string json = JsonConvert.SerializeObject(Result, Formatting.None);
 return json;
}     

And then i pass it to the controller.

It's ok - except one thing - controller itself is serializing the request and i get a double serialized json string with back slashes (here is a part of a json):

[{\"account\":\"121\",\"balance\":-348}]

I can't figure out how else can i pass the EnumerableRowCollection (not using a json string), so that i wont get a double serialized json? (or maybe i shouldnt convert it to a EnumerableRowCollection at all?)

Eve
  • 101
  • 2
  • 13

1 Answers1

0

All a WebAPI can return is the serialized representation of the object you want to return.

In this code, you're serializing an object into a JSON string, and then that string is encoded again to become a JSON string. This causes the double quoting.

You don't need to serialize the object yourself, and there's no use for using an EnumerableRowCollection indeed. Create a DTO:

public class AccountBalanceModel
{
    public string Account { get; set; }
    public decimal Balance { get; set; }    
}

Then return that from your API method, and let WebAPI deal with the serialization:

public IList<AccountBalanceModel> GetResult(DataTable dt)
{
    var model = dt.AsEnumerable().Select(row => new AccountBalanceModel
                {
                    Account = (string)row["ACCOUNT_ID"],
                    Balance = (decimal)row["BALANCE"]
                }).ToList(); 

    return model;
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272