REST Services

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 Dhananjay Kumar

Dhananjay Kumar is Developer, Blogger , Speaker, Learner , Mindcracker & Microsoft MVP.

Discussion

14 Responses to “WCF REST Service with JSON Data”

  1. Kool info

    Posted by uday | May 15, 2011, 11:03 pm
  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 .

    Posted by Hassan Humayun | June 2, 2011, 12:15 pm
  3. Hey Thanks for sharing the sample. This is really helpful for initial stage in Rest Wcf

    Posted by Anonymous | August 30, 2011, 5:24 pm
  4. Thanks i find the solution after wasting lot time on the blogs that provide false solutions thank u vry much

    Posted by Akhtar Hussain | October 21, 2011, 4:24 pm
  5. 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.

    Posted by Geeth | October 27, 2011, 10:53 pm
  6. 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

    Posted by Akhtar Hussain | November 14, 2011, 10:10 am
  7. 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;

    }

    Posted by ahmar | November 22, 2011, 10:28 am
  8. Thanks DJ! Nice Article for starting with JSON

    Posted by Jean Paul | December 19, 2011, 10:53 am
  9. Thanks Dhanajay, It was realy a great help to meet the deadlines of the Project.

    Regards,
    Manas & Rudra

    Posted by manas | March 21, 2012, 4:42 pm
  10. 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());

    Posted by John Tan | April 23, 2012, 2:39 pm
  11. Please provide me more details of error

    Posted by Dhananjay Kumar | May 1, 2012, 7:44 pm
  12. 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; }
    }

    }

    Posted by Jacob | May 18, 2012, 5:11 pm

Trackbacks/Pingbacks

  1. Pingback: Distributed Weekly 103 — Scott Banwart's Blog - May 20, 2011

  2. Pingback: Monthly Report May 2011: Total Posts 16 « debug mode…… - December 4, 2011

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 )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,380 other followers

Tweets

Categories

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway. © Copyright 2012