【问题标题】:Removing xml namespaces in C# restful web service returned string在 C# RESTful Web 服务中删除 xml 命名空间返回字符串
【发布时间】:2018-04-30 00:24:57
【问题描述】:

我正在使用 dot net framework 4.5 用 C# 编写的 restful API ..目前它工作正常...我在 JSON 转换后返回一个结果..我期待一个纯 JSON 结果...我目前没有得到。我期待一个简单的解决方案,在我返回 JSON 的根元素处省略字符串 XMLNS ...... 结果 我正进入(状态:

我的代码:

public String GetAllSalesInvoices(string customer_id, string Startdate, string Enddate)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        string query = "SELECT * FROM sales_invoice WHERE customer_id =" + customer_id + " AND invoice_date BETWEEN '" + Startdate + "' AND '" + Enddate + "'";
        DataSet ds = conObj.execQuery(query);
        DataTable dt = new DataTable();
        dt = ds.Tables[0];


        List<sales_invoice> result = new List<sales_invoice>();

        foreach (DataRow dr in dt.Rows)
        {
            sales_invoice inv = new sales_invoice()
            {
                Invoice_id = Convert.ToInt32(dr["invoice_id"]),
                Invoice_date = Convert.ToString(dr["invoice_date"].ToString()),
                Customer_id = Convert.ToInt32(dr["customer_id"]),
                Product_id = Convert.ToInt32((dr["product_id"])),
                Time = Convert.ToString((dr["time"]).ToString()),
                Quantity = Convert.ToInt32((dr["quantity"])),
                Unit_of_measure = Convert.ToString(dr["unit_of_measure"]),
                Product_price = Convert.ToInt32((dr["product_price"])),
                Sub_total = Convert.ToInt32((dr["sub_total"])),
            };
            result.Add(inv);
        }
        string json=serializer.Serialize(result);
        return json;
}

谢谢

【问题讨论】:

标签: c# json xml rest wcf


【解决方案1】:

大家好,我终于想出了一个删除 xml 命名空间或字符串命名空间作为回报的答案。 解决方案是使用上下文方法并将内容直接写入浏览器本身。为此,您可以使用此代码。

String result =js.Serialize(data);
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(result);

这将在没有任何命名空间的情况下将 json 序列化的原始数据写入浏览器。请注意,它不能在 restful api 的上下文中使用,因为那里的 this 可能有所不同。

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 1970-01-01
    • 2011-11-08
    • 2010-10-03
    • 2014-11-15
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多