简体   繁体   中英

WCF JSON Return Service should return Single Escape Sequence

What i am doing for changing html codes to JavaScript escapes is :

string input = "श्रीगंग..."

var output = Regex.Replace(input, @"&#([0-9]*);", 
               x => String.Format("\\u{0:X4}", int.Parse(x.Groups[1].Value)));
or alternately;

var output = String.Join("", WebUtility.HtmlDecode(input)
                   .Select(x => "\\u" + ((int)x).ToString("X4")));

But now i have a problem that when i am sending this data through wcf service in json format. and i am getting values accordingly. but only the output variable is going wrong which is in this format:

\\\&\\\#\\\2\\\3\\\3\\\7\\\;\\\&\\\#\\\2\\\3\\\7\\\5\\\;\\\&\\\#\\\2\\\3\\\3\\\8\\\;\\\&\\\#\\\2\\\3\\\6\\\4\\\;\\\ \\\&\\\#\\\2\\\3\\\2\\\5\\\;\\\&\\\#\\\2\\\3\\\5

i don't want '\\\&' but want only '\&' in response. i have tried everything like:

output.Replace("\\","'\'");
output.Replace("\\",@"\");

but didn.t work here.

Here is my WCF Service method:

 [OperationContract(Name = "GetByCity")]
        [WebInvoke(Method = "GET", UriTemplate = "/GetByCity/DeviceType={DeviceType}&CityId={id}&Limit={limit}", BodyStyle = WebMessageBodyStyle.WrappedRequest,
                    RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        NewsList GetByCity(string DeviceType, string id, string limit);

Now i don't know where to define utf-8 format.

The Unicode escpace sequence \\u.... is used in C# source code and it's used in JSON formatted data but it's not used in C# string. C# strings fully support Unicode and have a direct representation for all Unicode characters.

If required in the transmitted JSON data, the WCF service will create the escape sequence automatically. But if the strings already contain these escape sequences, then the WCF service will add more escaping so the unnecessary escape sequences will be retained after the JSON data has been parsed.

So in order to fix your problem, you will need to replace the HTML entites ( &#....; ) with the real Unicode character, ie श needs to be replaced with the character having the Unicode code point 2358:

var output = Regex.Replace(input, @"&#([0-9]*);", 
           x => new String((char) int.Parse(x.Groups[1].Value), 1) );

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