Posted by : my solutions Monday, December 17, 2012


Ultimately A Webservice response always in Xml Type format only. now we can change that format XML To JSON Format By using JScript Serializers


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Collections;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Data;
using System.Xml.Serialization;
using System.Xml;

/// <summary>
/// Summary description for jsonservice
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class jsonservice : System.Web.Services.WebService {

    public jsonservice () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod(Description = "getting json format type two")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string Getjsonformat()
    {
        SqlConnection conn = new SqlConnection(@"Data Source=PWHYD-123\SQLEXPRESS;Initial Catalog=sampledb1;Integrated Security=True");
        conn.Open();
        SqlCommand cmd = new SqlCommand("Select year,sales from graphs", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        DataTable dt = new DataTable("graphs");
        dt.Load(dr);
        dr.Close();
        conn.Close();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = new Dictionary<string, object>();
        foreach (DataRow datarow in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, datarow[col]);
            }
            rows.Add(row);
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string jsonData = serializer.Serialize(rows);
        return jsonData;
    }
 
}

----------------Happy Coding With P.M@ruthi-------------------

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © complete .net tutorials - Skyblue - Powered by Blogger - Designed by Johanes Djogan -