I recently had to expose a web-service as a RESTful JSON one using BizTalk 2013 R2 using the WCF-WebHttp adapter and a JSON decoder in the pipeline.  There are plenty of blogs about how to that and it is fairly straight forward.  However I had a bit of difficulty when a decision was made to use an existing XML schema and to allow the JSON equivalent of that.  This XML schema made extensive use of Attributes.

In XML you have elements and attributes, you don’t however have that distinction in JSON, so the first issue is, how do you represent an item in JSON that the BizTalk JSON decode will treat as an attribute.  With a bit of research I came across this wiki, JSON and XML Conversion, that highlight the fact that there is no single standard for representing XML attributes in JSON but instead several and none of them exactly match the standard that BizTalk uses

So to save you pain, here is how you represent XML attributes in JSON for BizTalk.  Attributes are denoted by a @ in the name and for any elements that have both and value and a attribute the value of the element is denoted as #text as a child.

Given an XML payload that looks like this.

<root rootAttribute="rootAttributeValue" xmlns="http://scratch/JSON">
  <element elementAttribute="elementAttributeValue">ElementValue</element>
  <record recordAttribute="recordAttributeValue">
    <childElement childElementAttribute="childElementAttributeValue">childElementValue</childElement>
    <repeatingChildElement repeatingChildElementAttribute="repeatingChildElementValue1">childElementValue1</repeatingChildElement>
     <repeatingChildElement repeatingChildElementAttribute="repeatingChildElementValue2">childElementValue2</repeatingChildElement>
  </record>
</root>

The JSON payload to represent it looks like this

{
   "@rootAttribute": "rootAttributeValue",
   "element": {
      "@elementAttribute": "elementAttributeValue",
      "#text": "ElementValue"
   },
   "record": {
      "@recordAttribute": "recordAttributeValue",
      "childElement": {
         "@childElementAttribute": "childElementAttributeValue",
         "#text": "childElementValue"
      },
      "repeatingChildElement": [
         {
            "@repeatingChildElementAttribute": "repeatingChildElementValue1",
            "#text": "childElementValue1"
         },
         {
            "@repeatingChildElementAttribute": "repeatingChildElementValue2",
            "#text": "childElementValue2"
         }
      ]
   }
}

A handy tool that will do this conversion for you is XML to JSON Converter with the default settings of Prefix attributes with: @ and #text property name: #text

Advertisements