Subscribe For Free Updates!

We'll not spam mate! We promise.

Sep 5, 2012

Return JSON Data From Asp.net Web Service

Views:

Return JSON Data From Asp.net Web Service
To Day i will share with you How to  Return JSON Data format From Asp.net Web Service. This is a very important tutorial that is extensively used in may software houses all over the world. This Technique is used for making mobile applications much fast, simpler and Cross plat-form supportive.
I already shared Features and qualities of JSON in my Article WHAT IS JSON .If you Don't know about JSON Please Read it first.

As we know that JSON (JavaScript Object Notation) is a lightweight , text-based open standard  format for exchanging objects .


Due to its light Weight when we Return 1,000 of (or above) records form web Service in JSON Format ,
1)  It doesn't Hang our Mobile Application.
2) The Charges for GPRS Service Provided by GSM or Mobile Network Company is also Reduced due light and small amount of data Transfer .
3) Lets Suppose we develop application For Our Client in Android, But Now he wants the same application on iPhone ,windows Phone 7 ,Symbian and BlackBerry  etc, So we can Convert It easily in any Other Platform Because JSON is easily  Access and Parsed   by Almost All (Smart Phone) Programming Languages.

Request Or Advice :
A simple Request is that when ever you Develop a Smart Phone Application always Put your Logic on server or on web service. Lets Explain through a simple Example of Calculator .
Suppose you have to Develop scientific Calculator on android, First Make a web Service, put all Logic's of Calculator on this Service . Now on phone level Just Pass arguments to  this Service and In Return Get results from Service irrespective of where you Pass Augments from i.e. Android ,iPhone ,Windows Phone 7 ,Symbian or Black Berry etc you will be Getting Results From Service only. I think Now you Understand the Point im trying to make regarding why this method is recommended.

So Lets Start :

I already Shared how to make Simple Asp.net Service, If you don't know read it first .
After Making Asp.net Web Service Create a Table With Following Structure .
USE [dbVisualStudioLearn]
GO

/****** Object:  Table [dbo].[tblUserInfo]    Script Date: 09/04/2012 19:22:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tblUserInfo](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Name] [nchar](20) NULL,
 [MajorSubjects] [nchar](50) NULL,
 [Univesity] [nchar](50) NULL,
 [IsActive] [bit] NULL
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[tblUserInfo] ADD  CONSTRAINT [DF_tblUserInfo_Date]  DEFAULT (getdate()) FOR [Univesity]
GO

ALTER TABLE [dbo].[tblUserInfo] ADD  CONSTRAINT [DF_tblUserInfo_IsActive]  DEFAULT ((1)) FOR [IsActive]
GO

Return JSON Data From Asp.net Web Service


 With Sample Data .
Return JSON Data From Asp.net Web Service

Now Create a Class with Name "dbcon" in Asp.net Web service  Project Code is Below :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace WebService1
{
    public class dbcon
    {
        SqlConnection CON;
        SqlCommand CMD;
        public dbcon()
        {
            CON = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbVisualStudioLearn;Integrated Security=True");
        }


        public DataSet GetDataTable(string query)
        {
            DataSet dt = new DataSet(); ;
            CON.Open();
            CMD = new SqlCommand(query,CON);
            dt.Tables[0].Load(CMD.ExecuteReader());
            //dt.fill();
            return dt;
        }
        public DataSet GetDataSet(string query)
        {
            
            SqlDataAdapter adapter = new SqlDataAdapter(query, CON);
                        DataSet customers = new DataSet();
            adapter.Fill(customers, "Customers");
            return customers;
        }
    }
}

Before Web Code in Service1.asmx We have to add Reference "Newtonsoft.Json" you can Download it from
1) JSON.NET
2)  JSON.NET RAR (Google Docs)
3)  JSON.NET.dll RAR (Google Docs)

Now Create tow method in Service1.asmx File Having Following Code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Services;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace WebService1
{
    //www.visulaStudiolearn.com
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public DataSet GetDataXML()
        {
            dbcon db = new dbcon();
            DataSet r = db.GetDataSet("select * from tblUserInfo");
            return r;
            
        }
        [WebMethod]
        public string  GetDataJSON()
        {
            dbcon db = new dbcon();
            DataSet r = db.GetDataSet("select * from tblUserInfo");
            string s = JsonConvert.SerializeObject(r); 
            return s;   
        }
    }
}

Line which convert DataSet to Json is Below it Take Object as Argument (Data Set ,Data Table,List Etc).
            string s = JsonConvert.SerializeObject(r); 

SO Now Run the Application Out put Screen Short is Below:
Return JSON Data From Asp.net Web Service
When you Click GetDataJSON Output Screen is Below:

Return JSON Data From Asp.net Web Service

and When you click GetDataXML Out put Screen is Below

Return JSON Data From Asp.net Web Service



















Download Source Code (Google Docs)

OR

Download Source Code (4 shared)



Plese Feel Free to Socializer This Post
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments:

Post a Comment

Become a Fan

visual studio learn