0

i have used the Newtonsoft.Json for converting data into json format.

I have write the below code:

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string DataTableToJSONWithJSONNet()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("id", typeof(Int32));


    DataSet ds = new DataSet();
    ds = cls.ReturnDataSet("Get_data",
          new SqlParameter("@Yourid", "5"));

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));

    }

    string JSONString = string.Empty;
    JSONString = "{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}";
    return JSONString;
}

So it gives me the below output:

enter image description here

But i want the output like :

{"mydata":[{"id":125},{"id":137},{"id":249},{"id":201},{"id":124},  
      {"id":173},{"id":160},{"id":153},{"id":146},{"id":168}]} 

So how can i convert to it from xml to json. ?

  • 6
    What's the difference between the 2 outputs? – Andreas Schwarz Apr 14 '16 at 07:27
  • Are you setting the request content type to application/json at the client side? – elvin Apr 14 '16 at 07:30
  • @AndreasSchwarz Sorry . please check the image. –  Apr 14 '16 at 09:14
  • @elvin sorry. Please check the image –  Apr 14 '16 at 09:14
  • if you are working on webservices see http://stackoverflow.com/questions/17235928/webservice-ignores-responseformat-json if you are working on webapi see http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome – user890255 Apr 14 '16 at 13:38

2 Answers2

2

I run your solution in a console application and I can clearly see the problem. If you avoid building json manually, the problem will go away. As I don't have database, I have added my data rows manually. Hope that will help.

using Newtonsoft.Json;
using System;
using System.Data;
namespace Test
{
    class MyDataContainer
    {
        public DataTable mydata { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write(DataTableToJSONWithJSONNet());
            Console.Read();
        }
        static string DataTableToJSONWithJSONNet()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(Int32));

            dt.Rows.Add(1);
            dt.Rows.Add(2);
            MyDataContainer cont = new MyDataContainer();
            cont.mydata = dt;
            string JSONString = string.Empty;
            JSONString = JsonConvert.SerializeObject(cont);
            //to see your attempt uncomment the blow lines
            //Console.Write("{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}");
            //Console.WriteLine();
            return JSONString;
        }      
    }   
}
user890255
  • 458
  • 5
  • 9
0

Looking into your codes, you are already declared that your output is type of JSON, so on the response data it will return a JSON string.

[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]

And you also declared that this is a ScriptMethod. My thought is you are testing your app by running your code and accessing the url of the web service - for example http://localhost/test.asmx and clicking the invoke button on your DataTableToJSONWithJSONNet method. This approach will really display JSON result enclosed on XML format. The best way to test your own code is to invoke the web service using something like jQuery Ajax or equivalent (client scripts).

You can change your code to something like this to achieve the output you are looking for:

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyResponse DataTableToJSONWithJSONNet()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("id", typeof(Int32));


    DataSet ds = new DataSet();
    ds = cls.ReturnDataSet("Get_data",
          new SqlParameter("@Yourid", "5"));

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));

    }

    MyResponse result = new MyResponse();
    result.mydata = dt;
    return result;
}

class MyResponse
{
    private object _mydata;
    public object mydata { get { return this._mydata; } set { this._mydata = value; } }
    public MyResponse() { }
}
Arnel Aves
  • 87
  • 5