Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude xml from json

Tags:

c#

xml

json.net

I'm using the below code to retrieve data in json format using web service But getting result in both XML and json format. Below is the code

[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", "[email protected]" });
        table.Rows.Add(new[] { "2", "1234567", "[email protected]" });
        table.Rows.Add(new[] { "3", "7654321", "[email protected]" });

        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  ;

    }

below is the output i'm getting...

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

I want the result only in Json

like image 663
user2176932 Avatar asked Feb 15 '26 01:02

user2176932


1 Answers

Use ScriptMethod attribute with ResponseFormat set to ResponseFormat.Json:

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

Additionally, your class has to be marked with [ScriptService] attribute.

like image 138
MarcinJuraszek Avatar answered Feb 16 '26 15:02

MarcinJuraszek