WCF Web服务返回带有额外反斜杠的JSON字符串

时间:2011-11-18 19:50:15

标签: wcf json web-services

我有一个返回JSON的Web服务。通过浏览器或测试程序测试程序时,字符串总是添加额外的反斜杠。例如,如果我希望我的输出看起来像:

{"ack":{"qry":[{"retn":"abcd","desc":"defg"}] 

它实际上显示为

{\"ack\":{\"qry\":[{\"retn\":\"abcd\",\"desc\":\defg\"}.

我正在使用JSON.NET和JsonTextWriter来创建字符串。

private string jsonParse(string respStr)
    {
        string jSonStr;
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);

        JsonWriter writer = new JsonTextWriter(sw);
        writer.Formatting = Formatting.None;

        List<string> commands = (from word in respStr.Split(':') select word).ToList();
        for (int j = 0; j < commands.Count; j += 3)
        {
            List<string> param = (from par in commands[j + 2].Split(new Char[] { ',', '=' }) select par).ToList();

            writer.WriteStartObject();
            writer.WritePropertyName(commands[j]);
            writer.WriteStartObject();
            writer.WritePropertyName(commands[j + 1]);
            writer.WriteStartArray();
            writer.WriteStartObject();
            for (int i = 0; i < param.Count - 1; i += 2)
            {
                writer.WritePropertyName(param[i]);
                writer.WriteValue(param[i + 1]);
            }
            writer.WriteEndObject();

            writer.WriteEndArray();
            writer.WriteEndObject();
            writer.WriteEndObject();
        }
        jSonStr = sb.ToString();

        return jSonStr;
    }

我的网络服务的操作合同如下:

[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json, UriTemplate="/{system}/{command}")]
string getMethod(string system, string command);

最后我用来测试的程序使用HttpWebRequest,如下所示:

HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = "GET";

Console.WriteLine("Sending GET Request");
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
Stream GETResponseStream = GETResponse.GetResponseStream();
StreamReader sr = new StreamReader(GETResponseStream);

Console.WriteLine(sr.ReadToEnd());

为什么会发生这种情况的任何线索?

1 个答案:

答案 0 :(得分:3)

不确定为什么会发生这种情况(可能会将字符串双重编码为​​JSON字符串)但是我可以建议您最好不要使用JSON .Net而是使用DataContracts - 它更简单并且意味着您的服务不需要知道它正在运行的基础设施。如果你这样定义你的方法:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{system}/{command}")]
Response getMethod(string system, string command);

然后对Response对象执行类似的操作:

[DataContract]
public class Response
{
    [DataMember(Name = "ack")]
    public Acknoweldge Acknowledge { get; set; }
}

[DataContract]
public class Acknoweldge
{
    [DataMember(Name = "qry")]
    public IEnumerable<Query> Query { get; set; }
}

[DataContract]
public class Query
{
    [DataMember(Name = "desc")]
    public string Description { get; set; }

    [DataMember(Name = "retn")]
    public string Return { get; set; }
}

然后像这样实现你的方法(我只返回一个虚拟对象):

public Response getMethod(string system, string command)
{
    return new Response
        {
            Acknowledge = new Acknoweldge
                {
                    Query = new List<Query>
                        {
                            new Query { Return = "abcd", Description = "defg" }
                        }
                }
        };
}

运行客户端代码示例,您将获得所需的结果,特别是:

{"ack":{"qry":[{"desc":"defg","retn":"abcd"}]}}