DaveB
DaveB

Reputation: 2229

WCF Web Service returning JSON string with extra backslahes

I have a web service that is returning JSON. When testing the program, either through a browser or a test program, the string always has extra backslashes added. For example, if I am expecting my output to look like:

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

it is actually showing up as

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

I am using JSON.NET and JsonTextWriter to create the string.

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;
    }

the operation contract for my web service looks like this:

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

and finally the program I'm using to test uses HttpWebRequest like so:

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());

any clue as to why this is happening?

Upvotes: 0

Views: 1347

Answers (1)

kmp
kmp

Reputation: 10885

Not sure why it is happenening (probably double encoding a string into a JSON string) but can I suggest that you would be better off not using JSON .Net for this and instead using DataContracts - it is much simpler and means your service does not need to know about the infrastructure it is running on. If you define your method like so:

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

And then do something like this for the Response object:

[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; }
}

Then implement your method like so (I just return a dummy object):

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

Running your client code sample you will get the result you are looking for, specifically:

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

Upvotes: 3

Related Questions