1

This is my web service IRestService.cs

 {

   [ServiceContract]
     public interface IRestServiceImpl
      {
        [OperationContract]
        [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "json/{id}")]
        string JSONData(string id);


        }
         }

This my JSON Helper Class

   public class JSONHelper
    {
      public static string ToJSON(this object obj)
      {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);
       }

    public static string ToJSON(this object obj, int recursionDepth)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        return serializer.Serialize(obj);
      }

My Service in which I am parsing a JSOn format type of string

    public class RestServiceImpl : IRestServiceImpl
    {
    #region IRestServiceImpl Members

    public string XMLData(string id)
    {
        return "You requested product " + id;
    }

    public string JSONData(string id)
    {
        id = @"{""contacts"":   [{""country"":""Pakistan"",""sunrise"":1381107633,""sunset"":1381149604}]}";
         return id;
    }

    #endregion

    }
  }

and this is the link i am using and getting Wrong JSON

http://116.58.61.180/Website/RestServiceImpl.svc/json/22

and JSON is

    {"JSONDataResult":"{\"contacts\":   [{\"country\":\"Pakistan\",\"sunrise\":1381107633,\"sunset\":1381149604}]}"}

What I am doing Wrong? Why I am getting backslash in this JSON

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Malaika Khan
  • 89
  • 2
  • 10

3 Answers3

0

Your return type is "string" and you are returning a JSON string which has double quotes in it. To escape it, WCF adds backslashes.

To get rid of it you should implement a return type of System.IO.Stream in WCF. It is just a serialized form of the string.

JunaidKirkire
  • 878
  • 1
  • 7
  • 17
  • {"JSONDataResult":"{\"contacts\":[{\"country\":\"Pakistan\",\"sunrise\":1381107633,\"sunset\":1381149604}]}"} please help me in this correction – Malaika Khan Jan 15 '15 at 07:42
  • Add this at the end of your method before returning byte[] x = Encoding.UTF8.GetBytes( << your JSON string goes here >>); WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; return new MemoryStream(x); Also make sure your method return types are "System.IO.Stream" – JunaidKirkire Jan 15 '15 at 08:25
0

use some sort of json serializer that lets you serialize c# objects to json like this

Jester
  • 3,069
  • 5
  • 30
  • 44
0

You can return object or list of objects.Have a look at below sample code. There is one GET method and one is POST. One method will return object of RequestData and one will return List of RequestData

[ServiceContract]
public interface IDataService
{
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
    List<RequestData> GetUser(Request data);

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "UsersList/{id}",RequestFormat=WebMessageFormat.Json)]
    RequestData UsersList(string id);



}

public class DataService : IDataService
{

    public List<RequestData> GetUser(Request data)
    {
        List<RequestData> list = new List<RequestData>();
        if (data.Name.ToUpper() == "MAIRAJ")
        {
            list.Add(new RequestData
            {
                Name = "Mairaj",
                Age = 25,
                Address = "Test Address"
            });
            list.Add(new RequestData
            {
                Name = "Ahmad",
                Age = 25,
                Address = "Test Address"
            });
            list.Add(new RequestData
            {
                Name = "Minhas",
                Age = 25,
                Address = "Test Address"
            });
        }
        return list;
    }
    public RequestData UsersList(string userId)
    {
        if (userId == "1")
        {
            return new RequestData
            {
                Name = "Mairaj",
                Age = 25,
                Address = "Test Address"
            };
        }
        else
        {
            return new RequestData
            {
                Name = "Amir",
                Age = 25,
                Address = "Test Address"
            };
        }
    }

}
[DataContract]
public class RequestData
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public int Age { get; set; }
    [DataMember]
    public string Address { get; set; }

}

And here is web.config

<configuration>
<configSections>
</configSections>
<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
</system.web>

<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="EndpBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="WCFWebApp.DataService">
    <endpoint address="" binding="webHttpBinding" contract="WCFWebApp.IDataService" behaviorConfiguration="EndpBehavior"/>
  </service>
</services>
</system.serviceModel>
</configuration>
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40