Click here to Skip to main content
15,889,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having an operationContract in WCF whose return type is an object and I need to send that object in JSON format to user. Now I have come across two ways of returning JSON data from my method. Please suggest which one is the good practice to adopt?; Does serializing the model as done in second way provides any additional benefits?

What I have tried:

The two ways of returning JSON data from my OperationContract are as followed:-
1)
[OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        public Model1 GetData(string Id1, string Id2)
        {
            try
            {
                Model1 objModel  = new Model1();
                DataSet ds = new DataSet();
                BAL objBAL = new BAL();
                objModel  = objBAL.GetData(Id1, Id2);
                return objModel  
            }
            catch (FaultException ex)
            {
                // error handling code here
            }
        }



2)
 [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        public string GetData(string Id1, string Id2)
        {
            try
            {
                string json = string.Empty;
                Model1 objModel  = new Model1();
                DataSet ds = new DataSet();
                BAL objBAL = new BAL();
                objModel  = objBAL.GetData(Id1, Id2);
                json = new JavaScriptSerializer().Serialize(objModel);
                return json;
            }
            catch (FaultException ex)
            {
                // error handling code here
            }
        }
Posted
Updated 15-Feb-18 8:56am
v3

1 solution

The first option will return a JSON-encoded representation of the result.

The second option will return a JSON-encoded string containing a JSON-encoded representation of the result.

Aside from the extra work involved on the server to JSON-encode the result twice, the second option will also require extra work on the receiving end.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900