简体   繁体   中英

WCF web service returning json format data

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM