通过 c# web 服务没有得到正确的 JSON

Not getting proper JSON through c# 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);


        }
         }

这是我的JSON帮手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);
      }

我正在解析 JSOn 格式类型字符串的服务

    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

    }
  }

这就是我正在使用的 link 并且出错了 JSON

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

并且JSON是

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

我做错了什么? 为什么我在 JSON

中出现反斜杠

您的 return 类型是 "string" 并且您正在 returning 一个 JSON 字符串,其中有双引号。为了转义它,WCF 添加了反斜杠。

要摆脱它,您应该在 WCF 中实现 return 类型的 System.IO.Stream。它只是字符串的序列化形式。

使用某种 json 序列化程序,让您可以将 c# 对象序列化为 json,例如 this

您可以 return object or list of objects。请查看下面的示例代码。 GET方法有一种,一种是POST。一种方法将 return RequestData 对象,一种方法将 return 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; }

}

这里是 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>