Search code examples
xmlwcfjsonserializationwcf-web-api

How do I serialize/deserialize a JsonValue object to and from XML in a WCF web service utilitzing Web Api?


So I have been working on a WCF web service using latest Web API assembly and I am loving the JsonValue object.

What I want to do is accept JSON which is bound to a JsonValue object, then convert that JsonValue object to a equivalent XML representation that can be passed into a stored procedure for processing. This eliminates the need to create objects to bind the JsonValue to and this keeps things fluid.

Then I would like to be able to select data out of the database in XML form and then convert that to JsonValue to be returned to the client.

I have been able to do convert the JsonValue to a string representation of XML by this extension method:

// Convert JsonValue to XML string
public static string ToXmlString(this JsonValue instance) {
    using (var ms = new MemoryStream()) {
        using (var xdw = XmlDictionaryWriter.CreateTextWriter(ms)) {
            instance.Save(xdw);
            xdw.Flush();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}

Is there a better way to do this? This method is fine but I was just wondering.

I have also been able convert XML string value back to a JsonValue using Json.NET library to convert the XML string to a JSON string and then load the string into a JsonValue object like so:

// Return JSON representation of XML
return JsonValue.Parse(JsonConvert.SerializeXNode(xmlElement, Formatting.None, true));

This approach is fine but I would like to not have to be dependent on the Json.NET library since I am including it solely for this one method. Is there a way to do this without using the Json.NET library?

Thanks in advance for any help!

Daniel


Solution

  • Your conversion code is good. To convert back from XML into JsonValue, you can use the JsonValueExtensions class in the Web APIs:

    // Convert JsonValue to XML string
    public static string ToXmlString(this JsonValue instance) {
        using (var ms = new MemoryStream()) {
            using (var xdw = XmlDictionaryWriter.CreateTextWriter(ms)) {
                instance.Save(xdw);
                xdw.Flush();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
    
    // Convert XML string to JsonValue
    public static JsonValue FromXmlString(this string jsonAsXml) {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonAsXml))) {
            using (var xdr = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max))) {
                return JsonValueExtensions.Load(xdr);
            }
        }
    }