3

I have created a WCF webservice returning json format data. My code is like below:

String sJSONdata = "";

StreamReader reader = new StreamReader(data);
sJSONdata = reader.ReadToEnd();

//'now convert the JSON into a data table
DataTable dt = GetJSONTable(sJSONdata);
dt.TableName = "Customer";

Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (DataRow rs in dt.Rows)
{
    dict = new Dictionary<string, string>();
    foreach (DataColumn col in dt.Columns)
    {
        dict.Add(col.ColumnName, rs[col].ToString());
    }
}
return (new JavaScriptSerializer().Serialize(dict));

And I get the following output:

{ "SampleServiceResult": "{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}" }

But I want the output as below:

{ "SampleServiceResult": {"Id":"1","Name":"xyz","email":"xya@test.com"} }

In the output it adds "\" escape character. How can I remove this and return valid json?

I have tried to replace "\" but it doesn't work.

Thanks

jsanalytics
  • 13,058
  • 4
  • 22
  • 43
Rajesh Pandya
  • 1,540
  • 4
  • 18
  • 31
  • Any reason why you're using a table? Data looks more suited to being a proper class to serialize/deserialize to/from.... and where are you looking at the output? if inside the debugger then you'll see the quotes as \" as you have double quotes inside strings. Is this output actually what you see in the client? – GPW Nov 09 '17 at 09:44
  • On closer inspection, your result dictionary has a single entry with a key of `"SampleServiceResult"` and a value of `"{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}"` (which is a *single string*). This suggests your actual problem is that the `GetJSONTable()` method is returning a single column whereas you appear to expect more than one? as I said above, serialize into a class that matches the data rather than trying to use a datatable unless the data varies by a lot. – GPW Nov 09 '17 at 09:47
  • @GPW, Yes I get same out put in client side. I have checked output in postman and in ios device. – Rajesh Pandya Nov 09 '17 at 10:15
  • Possible duplicate of [How do I return clean JSON from a WCF Service?](https://stackoverflow.com/questions/2086666/how-do-i-return-clean-json-from-a-wcf-service) – GPW Nov 09 '17 at 10:46
  • See link - basically you shouldn't return JSON from Web services (create a RESTful service instead), but you should also return an OBJECT (don't try to turn it into a string yourself, let the service do the serialization for you). Finally, don't mess about with a dictionary. if you know what the data looks like, define a class that looks the same and use THAT instead - you then don't need to mess about with dictionaries and data tables. – GPW Nov 09 '17 at 10:48

2 Answers2

4

I have got the expected out by applying following changes in my code:

  1. Changed return type from String to Stream
  2. Replaced the below code

    return (new JavaScriptSerializer().Serialize(dict));

    with

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; return new MemoryStream(Encoding.UTF8.GetBytes(sData));

Thanks everybody for help and support. May it will help someone.

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
Rajesh Pandya
  • 1,540
  • 4
  • 18
  • 31
2

It is better to let WCF take care of the serialization rather then doing it yourself.

You can use WebGet attribute and specify the response format for your operation contract.

Also, as pointed out in the comments, you could return your own .NET class instead of a Dictionary.

The operation contract could be something similar to this:

[OperationContract]
[WebGet(UriTemplate = "/GetCustomer", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
Customer GetCustomer();

with the following data contract:

[DataContract]
public class Customer
{
    [DataMember]
    public string Id { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Email { get; set; }
}

You could then implement the operation contract with code similar to this:

public Customer GetCustomer()
{
        Customer customer = GetCustomerData(); //Get the data and return a customer object
        return customer;
}
S.Dav
  • 2,436
  • 16
  • 22