Tony
Tony

Reputation: 2076

Using JSON.NET to serialize to XmlDictionaryWriter

I am converting all of our projects to use JSON.NET rather than DataContractJsonSerializer. How do I use JSON.NET to write to an XmlDictionaryWriter?

Current Implementation (using DataContractJsonSerializer):

public class ErrorBodyWriter : BodyWriter
{
    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        if (Format == WebContentFormat.Json)
        {
            // How do I use json.net below?
            var serializer = 
                new DataContractJsonSerializer(typeof(ErrorMessage));
            serializer.WriteObject(writer, Error);
        }
        else { // xml }
    }
    public ErrorBodyWriter() : base(true){}
    public ErrorMessage Error { get; set; }
    public WebContentFormat Format { get; set; }
}

Upvotes: 0

Views: 870

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87308

You can't do that directly. WCF is primarily XML-based, and to support JSON it was defined a JSON-to-XML mapping which if one wrote XML in a very specific format, and the underlying XML writer could produce JSON, then the proper JSON would be output.

The default WCF JSON serializer (DataContractJsonSerializer) knows how to write JSON to a XML writer using that mapping. JSON.NET doesn't. So one option is to write to a memory stream using JSON.NET, then read it into XML using the WCF JSON/XML reader, then use that to write to the XmlDictionaryWriter. The code would look somehow like the snippet below (written on notepad, some kinks may need to be addressed):

public class ErrorBodyWriter : BodyWriter
{
    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        if (Format == WebContentFormat.Json)
        {
            var json = JsonConvert.SerializeObject(Error);
            var jsonBytes = Encoding.UTF8.GetBytes(json);
            using (var reader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max)) {
                writer.WriteNode(reader, false);
            }
        }
        else { // xml }
    }
    public ErrorBodyWriter() : base(true){}
    public ErrorMessage Error { get; set; }
    public WebContentFormat Format { get; set; }
}

Upvotes: 1

Related Questions