Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Serializing in Json with Message Level Programming

.NET Framework 4.5

WCF supports serializing data in JSON format. This topic describes how to tell WCF to serialize your types using the DataContractJsonSerializer.

The DataContractJsonSerializer is used when the WebGetAttribute or the WebInvokeAttribute is applied to a service operation. Both of these attributes allow you to specify the RequestFormat and ResponseFormat. To use JSON for requests and responses set both of these to WebMessageFormat.Json. In order to use JSON you must use the WebHttpBinding which automatically configures the WebHttpBehavior. For more information about WCF serialization, see: Serialization and Deserialization, Serialization in Windows Communication Foundation. For more information about JSON and WCF see An Introduction to RESTfull Services with WCF, Creating JSON-enabled WCF Services in .NET 3.5, and Overview of REST in WCF.

Important note Important

Using JSON requires use of WebHttpBinding and WebHttpBehavior which do not support SOAP communication. Services that communicate with the WebHttpBinding do not support exposing service metadata so you will not be able to use Visual Studio’s Add Service Reference functionality or the svcutil command-line tool to generate a client-side proxy. For more information how you can programmatically call services that use WebHttpBinding, see How to Consume REST Services with WCF.

When working directly with untyped Message objects, you must explicitly set the properties on the untyped message to serialize it as JSON. The following code snippet shows how to do this.

 Message response = Message.CreateMessage(
                  MessageVersion.None,    // No SOAP message version
                             "*",                     // SOAP action, ignored since this is JSON
                             "Response string: JSON format specified", // Message body
                             new DataContractJsonSerializer(typeof(string))); // Specify DataContractJsonSerializer
      response.Properties.Add( WebBodyFormatMessageProperty.Name, 
                    new WebBodyFormatMessageProperty(WebContentFormat.Json)); // Use JSON format

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.