Serialize xConnect entities using JSON.NET

Current version: 9.0

This topic demonstrates how to serialize xConnect entities using JSON.NET. You may want to serialize xConnect objects if:

  • You want to cache facets in an external database.

  • You have a custom Web API endpoint that reads data using the xConnect client, acts on the data that is returned, and passes the modified data on to another service.


Keep international data privacy regulations in mind when writing contact and interaction data to a cache or database - for example, you may wish to avoid serializing contact facets marked [PIISensitive].

To serialize xConnect entities using JSON.NET, define a JsonSerializerSettings object as shown and pass this object into the SerializeObject method:

using Newtonsoft.Json;
using Sitecore.XConnect;
using Sitecore.XConnect.Client.Serialization;

namespace Documentation
    public class Serialize
        // Async example
        public async void SerializeEntities()
            using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                var serializerSettings = new JsonSerializerSettings
                    ContractResolver = new XdbJsonContractResolver(client.Model,
                serializeFacets: true,
                serializeContactInteractions: true),
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                    DefaultValueHandling = DefaultValueHandling.Ignore

                var contact = await client.GetAsync<Contact>(new IdentifiedContactReference("twitter", "myrtlesitecore"), new ContactExpandOptions() { });

                JsonConvert.SerializeObject(contact, serializerSettings);

Asynchronous and synchronous extension methods

In a unit testing context, you can use the Sitecore.XConnect.Serialization.DeserializationHelpers class to set read-only properties on the Contact and Interaction classes. The following example demonstrates how to use the SetFacet() method:

// New test contact
var contact = new Contact();

// New test contact facet
Sitecore.XConnect.Serialization.DeserializationHelpers.SetFacet(contact, PersonalInformation.DefaultFacetKey, new PersonalInformation() { FirstName = "Myrtle" } );

Do you have some feedback for us?

If you have suggestions for improving this article,