WCF REST Service with JSON Data

In this post I will show you working with WCF REST Service with JSON type of Data. I will discuss both POST and GET operation on data type JSON .

Creating Service

I have written much post on creating basic WCF REST Service. Please refer them if required.

WebGet Method

Let us create a Get method in WCF REST Service returning JSON type of Data. To return JSON type of data from WCF REST Service, we need to explicitly define message format as JSON in WebGet

clip_image002

In above GetMessageasJSON service

1. RequestFormat is of JSON type

2. ResponseFormat is of JSON type.

3. Above method is returning a string.

WebInvoke Method

Create one more method in WCF REST Service to POST JSON  Data

clip_image004

In above GetMessageasJSON service

1. RequestFormat is of JSON type

2. ResponseFormat is of JSON type.

3. Above method is returning an object of custom class Student.

4. Method is POST

5. Input parameter is an object of custom class Student.

Student is custom class and should be exposed as Data Contract. At client side all the custom classes can be distributed as a separate dll.

Eventually Service and Student class is as below ,

IService1.cs


using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace JQueryWCFREST
{

[ServiceContract]
public interface IService1
{

[OperationContract]
[WebGet(UriTemplate="/GetJOSNMessage",
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
String GetMessageasJSON();

[OperationContract]
[WebInvoke(UriTemplate = "/UplaodData",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Student GetUpdatedStudent(Student s);
}

[DataContract]
public class Student
{
[DataMember]
public string RollNumber { get; set; }
[DataMember]
public string Name { get; set; }
}
}

Service implementation is as below,

Service1.svc.cs


using System;

namespace JQueryWCFREST
{

public class Service1 : IService1
{
public String GetMessageasJSON()
{
return "Hi , I am JOSN DATA ";
}

public Student GetUpdatedStudent(Student s)
{
s.Name = "I have Updated Student Name";
return s;
}
}
}

Hosting Service

Hosting of JSON WCF REST Service can be done in exactly the same way as of default XML WCF REST Service.

Consuming Service

To call above service from ASP.Net or any Managed application, we will have to use below references.

clip_image006

Performing Get Operation

At the client side usual download of data with WebClient will do the work. To De Serialize data, we can use DataContractJSONSerializer

clip_image008

In above method,

1. Data is being downloaded as stream using WebClient

2. De Serialized data using DataContractJSONSerializer

Performing POST Operation

clip_image010

In above method,

1. POST operation is being performed using WebClient

2. Data is being serialized to JSON type using DataContractJsonSeeializer

For reference client side code to perform operation against JSON type WCF REST Service is as below,

Program.cs


using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using JQueryWCFREST;

namespace JSONClient
{
class Program
{
static void Main(string[] args)
{
#region Getting JOSN Data
WebClient proxy = new WebClient();
byte[] data = proxy.DownloadData( "http ://localhost:38395/Service1.svc/GetJosnmessage)
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();
Console.WriteLine(result.ToString());
Console.ReadKey(true);

#endregion

#region Uploading JOSN Data
Student student = new Student{Name ="Dhananjay",RollNumber ="9"};
WebClient Proxy1 = new WebClient();
Proxy1.Headers["Content-type"] = "application/json";
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(Student));
serializerToUplaod.WriteObject(ms, student);
data = Proxy1.UploadData(http://localhost:38395/Service1.svc/UplaodData", "POST", ms.ToArray());
stream = new MemoryStream(data);
obj = new DataContractJsonSerializer(typeof(Student));
var resultStudent = obj.ReadObject(stream) as Student;
Console.WriteLine(resultStudent.RollNumber+" " + resultStudent.Name);
Console.ReadKey(true);

#endregion

}
}
}

On running output expected is,

clip_image012

About these ads

19 thoughts on “WCF REST Service with JSON Data

  1. Pingback: Distributed Weekly 103 — Scott Banwart's Blog

  2. Thanks buddy , could you also explain the benefits of using REST based Services. The only advantage that i can see from your example is that one can access REST Services thru browser .

  3. Thanks i find the solution after wasting lot time on the blogs that provide false solutions thank u vry much

  4. Thanks Dhananjay,
    I found accurate information here on WCF REST POST JSON and also on how to pass /update and return objects using REST.
    Great one.

  5. how can we call the service from android program there we cannot have the webclient can not we use HTTP post with the above service

  6. to call from android use this code for post method
    ——————————————————————–
    public JSONObject PostObjext(StringEntity entity) throws Exception {
    if (this.url.equals(“”)) {
    throw new Exception(“Define the Url of Service”);
    }
    HttpClient httpClient = new DefaultHttpClient();
    try {
    HttpPost method = new HttpPost(new URI(url));
    method.setHeader(“Accept”, “application/json”);
    method.setHeader(“Content-type”, “application/json”);
    method.setEntity(entity);

    HttpResponse response = httpClient.execute(method);
    int stcode = response.getStatusLine().getStatusCode();
    if (response != null && stcode == 200) {

    String s = getResponse(response.getEntity());
    JSONObject returnedentity = new JSONObject(s);
    return returnedentity;
    } else if (stcode == 404) {
    throw new Exception(getError(response.getEntity()));
    } else {
    throw new Exception(“User Id already exists”);
    }
    } catch (IOException e) {
    Log.e(“error”, e.getMessage());
    return null;
    } catch (URISyntaxException e) {
    Log.e(“error”, e.getMessage());
    return null;
    } catch (JSONException e) {
    Log.e(“error”, e.getMessage());
    return null;
    }
    finally
    {
    httpClient = null;
    }
    ——————————————————————————————
    for get method
    ——————————————————————————————
    public JSONArray ExecuteService() throws Exception {
    if (this.url.equals(“”)) {
    throw new Exception(“Define the Url of Service”);
    }
    HttpClient httpClient = new DefaultHttpClient();
    try {
    HttpGet method = new HttpGet(new URI(url));
    HttpResponse response = httpClient.execute(method);
    int stcode = response.getStatusLine().getStatusCode();
    if (response != null && stcode == 200) {

    String s = getResponse(response.getEntity());
    JSONArray entries = new JSONArray(s);

    return entries;
    } else if (stcode == 404) {
    throw new Exception(getError(response.getEntity()));
    } else {
    throw new Exception(“Error accessing the Service”);
    }
    } catch (IOException e) {
    Log.e(“error”, e.getMessage());
    } catch (URISyntaxException e) {
    Log.e(“error”, e.getMessage());
    } catch (JSONException e) {
    Log.e(“error”, e.getMessage());
    }
    httpClient = null;
    return null;

    }

  7. Pingback: Monthly Report May 2011: Total Posts 16 « debug mode……

  8. Thanks Dhanajay, It was realy a great help to meet the deadlines of the Project.

    Regards,
    Manas & Rudra

  9. Hi, good article, thanks for sharing. But I got a problem. i followed your codes but I got an Http 400 error for this line
    byte[] data = proxy1.UploadData(“http://localhost:50557/WcfRest1/Service.svc/UploadData”, “POST”, ms.ToArray());

  10. Thanks Dhananjay for the great article. However I am not not able to recieve the Posted JSON on the WCF end. Any help is greatly appreciated. My GET operations are working perfectly fine. The cart object is coming out to be null at ‘Ship GetShipInfo( Cart cart, string Website)'; Here is the code.

    WCF

    public interface IService
    {

    [OperationContract]
    [WebInvoke(UriTemplate = "/cart", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
    Ship GetShipInfo( Cart cart, string Website);

    [OperationContract]
    [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Product/{GenderId}/{CategoryId}/{Website}")]
    List GetWebsiteSizes(string GenderId,string CategoryID, string Website);

    }

    [DataContract]
    public class Cart
    {
    [DataMember]
    public Int32 ProductID { get; set;}
    [DataMember]
    public decimal ItemPrice { get; set; }
    [DataMember]
    public Int16 Qty { get; set; }
    [DataMember]
    public String SizeWidth { get; set; }
    }

    CLIENT CALL

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Runtime.Serialization.Json;
    using System.Net;
    using System.IO;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
    Cart cart = new Cart{ ProductID = 1000, ItemPrice = Convert.ToDecimal(32.50), Qty = 1, SizeWidth = “6M” };
    WebClient Proxy1 = new WebClient();
    Proxy1.Headers["Content-type"] = “application/json”;
    MemoryStream ms = new MemoryStream();
    DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(Cart));
    serializerToUplaod.WriteObject(ms, cart);
    //MemoryStream ss = new MemoryStream();
    //ss = ms;
    byte[] data = Proxy1.UploadData(“http://localhost:54897/IphoneService.svc/cart”, “POST”, ms.ToArray());
    Stream stream = new MemoryStream(data);
    obj = new DataContractJsonSerializer(typeof(Ship));
    var Ship = obj.ReadObject(stream) as Ship;

    }

    public class Ship
    {
    public Decimal SecondDay { get; set; }
    public Decimal NextDay { get; set; }
    }

    public class Cart
    {

    public Int32 ProductID { get; set; }

    public Decimal ItemPrice { get; set; }

    public Int16 Qty { get; set; }

    public String SizeWidth { get; set; }
    }

    }

  11. Pingback: Consume a WCF web service with Post Params with Android | PHP Developer Resource

  12. Jacob, Make sure you used virtual directory if you have hosted on application server, or if this is local host the uri is incorrect

  13. Can you help me All DML operations perform in database using WCFREST service AND also consume this service in my ASP.NET pages?
    plz help me One simple Example

  14. Pingback: how to get information in asmx file from database n den convert that info into json | ASP Questions & Answers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s