2017-02-17 81 views
0

所以我有httpget請求,應該從我的數據庫返回一個datatable。我將我的數據表爲EnumerableRowCollection,然後序列化到JSON字符串(使用json.net):Httpweb請求數據表

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; 
}  

然後,我把它傳遞給控制器​​。

這是確定 - 除了一兩件事 - 控制器本身已被序列化的要求,我也得到一個雙串行化JSON字符串用反斜槓(這裏是一個JSON的一部分):

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

我想不通我怎麼能通過EnumerableRowCollection(不使用json字符串),以便我不會得到一個雙序列化json? (或者我可能不應該將它轉換爲EnumerableRowCollection?)

回答

0

WebAPI可以返回的所有內容都是要返回的對象的序列化表示形式。

在這段代碼中,您將對象序列化爲JSON字符串,然後該字符串再次被編碼爲JSON字符串。這會導致雙引號。

您不需要自己序列化對象,而且確實沒有必要使用EnumerableRowCollection。與序列

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

然後返回從您的API方法,讓這筆交易的WebAPI:創建一個DTO

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; 
} 
+0

泰!爲我工作。除了.ToList(),它只有在我調用return model.ToList()時才起作用 – Eve

+0

是的,這是一個小的語法錯誤,我通常使用流利的語法。 – CodeCaster