Edit

Share via


Serializing in Json with Message Level Programming

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

Typed Message Programming

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. For more information about JSON and WCF, see Service Station - An Introduction To RESTful Services With WCF.

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.

Untyped Message Programming

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  

See also