JSON and XML for REST

To illustrate the different between JSON and XML data that might be returned from a REST service, let's look at a small data sample, and see how it would be represented in each language. For this example, we'll use a list of file names that might be returned by a REST Service:

  • Image1.jpg
  • Description.docx
  • Forecast.xlsx
  • Agreement.pdf
  • NetworkDiagram.vsdx

XML

<?xml version="1.0"?>
   <Files>
      <item>Image1.jpg</item>
      <item>Description.docx</item>
      <item>Forecast.xlsx</item>
      <item>Agreement.pdf</item>
      <item>NetworkDiagram.vsdx</item>
   </Files>

The structured nature of XML limits how we can represent this data. We must have a "Files" node that contains all of the files. Each file needs its own "Item" node. Because XML is so highly structured, there are strict limits on how data can be represented.

JSON

JSON is much less structured than XML, and can present this same data in many ways.

Single Elements

{
   "Image":"Image1.jpg",
   "Document1":"Description.docx",
   "Spreadsheet":"Forecast.xlsx",
   "PDF":"Agreement.pdf",
   "Visio":"NetworkDiagram.vsdx"
}

Structured Array

[
   {"Files":"Image1.jpg"},
   {"Files":"Description.docx"},
   {"Files":"Forecast.xlsx"},
   {"Files":"Agreement.pdf"},
   {"Files":"NetworkDiagram.vsdx"}
]

Unstructured Array Elements

{
   "Files":
   [
      "Image1.jpg",
      "Description.docx",
      "Forecast.xlsx",
      "Agreement.pdf",
      "NetworkDiagram.vsdx"
   ]
}

Structured Array Elements

{
   "Files":
   [
      {"f":"Image1.jpg"},
      {"f":"Description.docx"},
      {"f":"Forecast.xlsx"},
      {"f":"Agreement.pdf"},
      {"f":"NetworkDiagram.vsdx"}
   ]
}

While this flexibility is nice, it does mean that you need to know, to a much greater degree than with XML, how the specific data you get in a response is structured, in order to parse and use it properly.

From an implementer's point of view, you may find XML REST Services easier to work with, if available, especially if you're just starting to use REST services. The structured nature of XML generally makes it more readable, and easier to understand.

More Information about Rest Services

REST Services: An overview of using REST Web Services.

JSONPath and XPath: A comparison of the XPath and JSON Path syntax needed to parse XML or JSON REST responses.