jueves, 17 de septiembre de 2015

XML vs JSON Based Web Services: Which is the Best Choice?

XML vs JSON Based Web Services: Which is the Best Choice?

Many mobile applications can get by without ever having to exchange information over the web, but if you're looking to build data-driven mobile applications, sooner or later you're going to have to communicate with a remote server. There are many different ways of accomplishing this goal. Some approaches are succinct and lightweight, while others are woefully inefficient and data-heavy. For mobile devices, which may be bound by a monthly data cap and slow connectivity speeds, we want to be as lightweight and efficient as possible.

Problems with HTML

In a perfect world, we'd have web services for every bit of data we'd ever want to consume, but sadly that's not the case. In one particular project here at Segue, we were reduced to having to submit form posts and scraping the HTML result. Imagine the impact this has on a mobile device. The string manipulation involved in parsing down the resulting HTML required a solid amount of coding. HTML can be heavy; it contains data we don't need, including images and markup language that are of no significance to us as pure data consumers. HTML is long because it contains many characters other than pure content, which translates to slow transfer speed and eats into monthly data transfer limits. It’s is also dynamic and prone to change (as if you haven't already discovered this), and will eventually destroy your parsing routine, which is the process of whittling down the entire HTML string into its useable components using string manipulation functions.

The Advantages of Web Services

A way to overcome the limitations of HTML is to use web services. For those who don't know, a web service can be thought of as a function call to a remote server and offers very specific functionality. Web services exist all over the web and many are open to the public. If you're fortunate, you might find one that meets your data requirements. If not, you could always build and host one yourself. The advantage of web services is that they are focused on a particular set of data, so you don't have to filter out information that is of no use to you. For example, say you wanted a weather forecast. You could call a web service and pass in a date and expect to get a resulting forecast for the date you submitted. This means we are dealing with a small set of data specifically focused on our need, which equals a smaller data size and faster transmission speed. However, not all web services are created equal. The breadth of various technical differences between web service types is too broad to tackle in a single blog post, but we will discuss the difference in return formats, because they can have a measurable impact on speed.

Return Formats

In my experience, I've encountered two primary web service return formats: XML and JSON.Extensible Markup Language (XML) has long been a popular way to structure data using familiar markup language. It is both human and machine readable and is very similar in appearance to HTML. It follows a set of standards for data communication over networks between devices and is iteratively parseable. One advantage of consuming data in this format is its structure. Data can be added or removed from the result set, but it will often exist in a predictable format so you don't have to worry about your parsing routine breaking when the data changes over time. Despite its advantages, one drawback of XML is its size, because it contains many characters strictly related to formatting. When downloading data to a mobile device, it would be ideal to just obtain the relevant content instead of data related to content formatting. This is where JSON comes in.
JavaScript Object Notation (JSON) is a text-based data interchange format derived from theJavaScript scripting language. It is formatted as key-value pairs and is often lauded as being a lower-overhead to XML because it focuses more on content and less on formatting. This works to our advantage when we want to keep data interchange packets as compact as we viably can. Now to be fair to XML, it is possible to format it in specific ways or use compression to make it comparable in size to JSON, but generally I find JSON to be much smaller in size and therefore preferable to XML.
One final observation (geared toward iOS since that is the particular platform for which I develop) focuses on how we process the two formats on the device once information has been returned from the web service. Parsing XML in iOS can be a bit tedious as it involves implementing a handful of NSXMLParserDelegate methods to iterate through the XML code. This can require a significant amount of coding. On the other hand, if a JSON object is returned from a web service we can convert it directly into native objects such asNSDictionary or NSArray. These objects can be archived and we can access data elements as key-value pairs without having to implement any delegate methods or iterate through the result data. This equates to a measurable increase in speed and efficiency. For my money, JSON is absolutely the way to go for mobile device data consumption.
What to Read Next:
json
JSON es un formato de intercambio ligero que al igual que el XML puede ser  leído fácilmente  y es independiente de la plataforma, esta basado en sub conjunto de javascript por esta razón puede ser convertido a javascript rápidamente y por lo tanto es ideal para aplicaciones Web basadas en AJAX, pero la ventaja de JSON sobre AJAX es que es capas de representar la misma información en un formato mas ligero que el XML y por lo tanto es mas rápido de transportar y consume menos ancho de banda.
Un ejemplo de un objeto serializado con ambos formatos:
Con XML:
<Product>
<ProductID>1</ProductID>
<ProductCode>p_1</ProductCode>
<ProductName>a Product 1</ProductName>
</Product>
Con JSON:
{“ProductID”:1,”ProductName”:”a Product 1″}
Como podemos ver con JSON nos ahorramos una cantidad de información que no es necesaria que viaje en las peticiones que hacemos por ejemplo a un Web services. Así que veamos que necesitamos para que nuestro servicio Web se comunique a través de JSON.
-Primero necestaremos que en nuestro archivo web.config contiene la sección correspondiente del objeto ScriptJsonSerializationSection
<section name=”jsonSerialization”
type=”System.Web.Configuration.ScriptingJsonSerializationSection,System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″
requirePermission=”false” allowDefinition=”Everywhere”/>
-Segundo configuraremos la clase de nuestro servicio Web para que use el atributo [System.Web.Script.Services.ScriptService]
[System.Web.Script.Services.ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
[WebMethod]
public string GetServerTime()
{
string serverTime =
String.Format(“The current time is {0}.”, DateTime.Now);
return serverTime;
}
}
-Tercero indicaremos a nuestro Web method el formato que utilizara con el atributo [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetServerTime()
{
string serverTime =
String.Format(“The current time is {0}.”, DateTime.Now);
return serverTime;
}
Si queremos enviar objetos ya serializado en JSON para ser consumidos desde javascript podemos hacerlo de la siguiente manera
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(yourObject.GetType());
//Creo un memory stream
MemoryStream ms = new MemoryStream();
//serializo el objeto en el Memory Steam
serializer.WriteObject(ms, yourObject);
//Convierto el objeto serializado en un string
string jsonString = Encoding.Default.GetString(ms.ToArray());
//close the memory stream
ms.Close();
Para deserializar un objeton tambien es muy sencillo, imaginemos que recibimos el objeto persona
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Persona));
ms.Position = 0;
Persona p = (Persona)ser.ReadObject(ms);
Con la utilizacion de JSON vemos como podemos disminuir de manera considerable la cantidad de datos que enviamos y recibimos al servidor lo cual convierte a nuestra aplicacion en un sistema mucho mas escalabre y que respondera mucho mejor ante una sobre carga de usuarios.
Blogger Widgets