【问题标题】:Httpweb request with datatable带有数据表的 Httpwebrequest
【发布时间】:2017-02-17 06:22:40
【问题描述】:

所以我有 httpget 请求,它应该从我的数据库中返回一个 datatable。我将我的数据表转换为 EnumerableRowCollection ,然后将其序列化为 json 字符串(使用 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;
}     

然后我将它传递给控制器​​。

没关系 - 除了一件事 - 控制器本身正在序列化请求,我得到一个带有反斜杠的双序列化 json 字符串(这里是 json 的一部分):

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

我不知道我还能如何传递EnumerableRowCollection(不使用 json 字符串),这样我就不会得到双序列化的 json? (或者我根本不应该将其转换为EnumerableRowCollection?)

【问题讨论】:

    标签: c# asp.net-web-api json.net


    【解决方案1】:

    WebAPI 可以返回的只是您要返回的对象的序列化表示。

    在此代码中,您将一个对象序列化为 JSON 字符串,然后该字符串再次被编码为 JSON 字符串。这会导致双引号。

    您不需要自己序列化对象,而且确实没有使用EnumerableRowCollection。创建 DTO:

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

    然后从你的 API 方法中返回,让 WebAPI 处理序列化:

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

    【讨论】:

    • 泰!为我工作。除了 .ToList(),它只有在我调用 return model.ToList() 时才有效
    • 是的,这是一个小语法错误,我一般使用流利的语法。
    猜你喜欢
    • 2019-01-17
    • 2011-08-27
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多