Sunday, April 27, 2014

HowTo send JSON data from WCF service with special characters

The manner to return special characters within the JSON response of a (SharePoint-based) WCF REST service, consists of 3 essential elements:
  1. Define the method response as System.IO.Stream;
  2. Set the charset of the JSON response to 'ISO-8859-1';
  3. Apply UniCode encoding to the JSON response string.
Code example
[ServiceContract(Namespace = "...")] public interface IRESTService { [WebInvoke(Method = "GET", UriTemplate = "/RESTMethod?$parameter1={parameter1}&...", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] System.IO.Stream RESTMethod(string parameter1, ...); } [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] public class RESTService : IRESTService { public Stream RESTMethod(string parameter1, …) { OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; context.ContentType = "application/json; charset=ISO-8859-1"; string jsonData = ...; return new MemoryStream(UnicodeEncoding.Default.GetBytes(jsonData)); } }

No comments:

Post a Comment