3

我正在使用以下代码使用 Web 服务检索 json 格式的数据,但同时获得 XML 和 json 格式的结果。下面是代码

[WebMethod(Description = "Get Employees")]
    public string getEmployees()
    {

        //List<employee> l=new List<employee>();
        //l.Add(new employee{ID=1,name="sreekanth"});
        //l.Add(new employee{ID=2,name="pradeep"});
        //l.Add(new employee{ID=3,name="swaroop"});
        //l.Add(new employee{ID=4,name="nagman"});
        //l.Add(new employee{ID=5,name="chethan"});
        //return l;
        DataTable table = new DataTable();
        table.Columns.Add("userid");
        table.Columns.Add("phone");
        table.Columns.Add("email");


        table.Rows.Add(new[] { "1", "9999999", "test@test.com" });
        table.Rows.Add(new[] { "2", "1234567", "foo@test.com" });
        table.Rows.Add(new[] { "3", "7654321", "bar@test.com" });

        var query = from row in table.AsEnumerable()
                    select new
                    {
                        userid = (string)row["userid"],
                        phone = (string)row["phone"],
                        email = (string)row["email"]
                    };

        JObject o = JObject.FromObject(new
        {
            Table = query
        });
        string result = JsonConvert.SerializeObject(o);
        //Console.WriteLine(o);

        return result  ;

    }

下面是我得到的输出......

 <?xml version="1.0" encoding="utf-8" ?> 
<string xmlns="http://tempuri.org/">{"Table":            [{"userid":"1","phone":"9999999","email":"test@test.com"},{"userid":"2","phone":"1234567","email":"foo@test.com"},{"userid":"3","phone":"7654321","email":"bar@test.com"}]}</string> 

我只想要 Json 中的结果

4

1 回答 1

2

使用设置为的ScriptMethod属性:ResponseFormatResponseFormat.Json

[WebMethod(Description = "Get Employees")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getEmployees()

此外,您的课程必须用[ScriptService]属性标记。

于 2013-03-16T12:13:18.427 回答