从WCF服务返回的JSON数据包含转义字符 [英] JSON data returned from WCF service contains escape characters

查看:1787
本文介绍了从WCF服务返回的JSON数据包含转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作WCF - WPF应用程序的工作,但是我正在寻找一些优化。 下面是我的code其中一个WCF RESTful服务是露出一个JSON阵列,并且WPF UI接收它没有任何问题。

I have a working WCF - WPF application working, however I'm looking for some optimization. Below is my code where a WCF restful service is exposing a JSON array, and a WPF UI is receiving it without any problem.

WCF:

public clsStatus[] GetAllStatus()
{

    DataTable dt = new DataTable();
    List<clsStatus> lstGetAllStatus = new List<clsStatus>();
    try
    {
        dt = // My Data Table

        foreach (DataRow dr in dt.Rows)
        {
            dcStatus objGetAllStatus = new clsStatus();
            objGetAllStatus.Id = Convert.ToInt32(dr["Id"]);
            objGetAllStatus.Status = dr["Status"].ToString();                   
            lstGetAllStatus.Add(objGetAllStatus);
        }

    }
    return lstGetAllStatus.ToArray();
}

在WPF界面:

public ObservableCollection<T> InvokeGet<T>(string sUrl)
{

    System.Net.WebRequest request = System.Net.HttpWebRequest.Create(sUrl);

    request.Method = "GET";

    request.UseDefaultCredentials = true;

    request.ContentLength = 0;

    System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;

    Stream objResponseStream = response.GetResponseStream();

    StreamReader reader = new StreamReader(objResponseStream);

    string objResponseString = reader.ReadToEnd();

    response.Close();

    JavaScriptSerializer objJsonserialiser = new JavaScriptSerializer();

    objJsonserialiser.MaxJsonLength = 999999999;

    T[] arrResult = objJsonserialiser.Deserialize<T[]>(objResponseString);

    return new ObservableCollection<T>(arrResult);  

}

这样的序列化/反序列化工作正常,而当我做所示的反序列化下面的变化不再起作用:

This way serialization/deserialization is working fine, whereas when I make the changes shown below the deserialization no longer works:

在WCF:

public string[] GetAllStatus()
{
    DataTable dt = new DataTable();

    try
    {
        dt = // My Data Table

        string jsonresp = JsonConvert.SerializeObject(dt, Formatting.None);
    }

    return jsonresp;
}

在WPF:

public ObservableCollection<T> InvokeGet<T>(string sUrl )
{

    System.Net.WebRequest request = System.Net.HttpWebRequest.Create(sUrl);

    request.Method = "GET";

    request.UseDefaultCredentials = true;

    request.ContentLength = 0;

    System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;

    Stream objResponseStream = response.GetResponseStream();

    StreamReader reader = new StreamReader(objResponseStream);

    string objResponseString = reader.ReadToEnd();

    response.Close();

    dsReportRequests dsrepreq = new dsReportRequests();

    //This conversion is failing with error
    dsrepreq = JsonConvert.DeserializeObject<dsReportRequests>(objResponseString);
}

错误:错误转换值\[{\ID \:11280,\STATNAME}] \键入'clsStat []'。路径',1号线,位置759。

我发现,JSON格式的改变code包含逃脱字符(<$ C C $> \ ),这似乎是导致错误反序列化。

I found out that the JSON format in the changed code contains escape chars (\), which seems to be causing the error while deserializing.

推荐答案

您JSON越来越双序列化。 (在JSON额外的反斜线对症这一点。)

Your JSON is getting double-serialized. (The extra backslashes in the JSON are symptomatic of this.)

在第一个版本的通知,你不要打电话到序列里面返回的对象GetAllStatus(),而在 InvokeGet()你打个电话来反序列化。并且工作。所以,从某种程度上GetAllStatus返回的对象一定是自动序列化。应该明确的是,WCF必须处理为您在返回对象的序列化。

Notice in the first version, you do not make a call to serialize the return object inside GetAllStatus(), but in InvokeGet() you do make a call to deserialize it. And that works. So, somehow the return object from GetAllStatus must be getting serialized automatically. It should be clear that WCF must be handling the serialization of your return object for you.

在第二个版本,手动序列里面返回的对象GetAllStatus()使用 JsonConvert.SerializeObject() 。因为我们刚刚建立的周转基金也在做系列化,你最终得到的双系列化的JSON。

In the second version, you manually serialize the return object inside GetAllStatus() using JsonConvert.SerializeObject(). Since we just established that WCF is also doing serialization, you end up with double-serialized JSON.

要使它工作,你需要确保输出只序列化一次。 presumably你有一个理由,开始在服务中使用Json.Net,所以我会寻找一种方式来代替WCF序列化与JSON.Net。你不必看far--有相当几个问题和答案的计算器上的处理这个题目。这里有一些想法:

To make it work, you need to ensure that the output is only serialized once. Presumably you had a reason to start using Json.Net in your service, so I would look for a way to replace the WCF serializer with JSON.Net. You don't have to look far-- there are quite a few questions and answers on StackOverflow that deal with this very topic. Here are few ideas:

  • replace WCF built-in JavascriptSerializer with Newtonsoft Json.Net json serializer (Synopsis: write a custom message formatter and configure WCF to use it)
  • Replace default JSON serializer in WCF 4 to JSON.NET (Synopsis: manually serialize to a stream and bypass WCF's serialization altogether)
  • WCF RESTful web service with JSON.Net: avoid double serialization (Synopsis: use Web API instead of WCF since it already uses Json.Net by default)

这篇关于从WCF服务返回的JSON数据包含转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆