Home > Articles > Programming > Java

📄 Contents

  1. Getting Started
  2. JavaScript Objects
  3. Serializing JavaScript Objects as JSON
  4. Deserializing JSON as Client-Side JavaScript Objects
  • Print
  • + Share This
Like this article? We recommend

Deserializing JSON as Client-Side JavaScript Objects

For this article, I’ve simply created a static file as the JSON response, but in a real application you could store this data in a database and return it via a server-side language. This capability creates an extremely powerful data-interchange process that can be achieved with ease! We’ve already looked at the serialization process. With basic AJAX experience, you should understand how that data can be posted to the server. Now let’s cover deserialization, starting with a static JSON file for this example. The file is actually the data that we’re serializing in the last section of the article:

{"Car":{"color":"#333","Wheel":{"color":"#000"}}}

As an example of a request to the JSON file, this serialized Auto object will be requested when we click the following link:

<a href="javascript:AjaxUpdater.Update(’GET’, ’json/data.js’, displayResponse);">Get remote JSON</a>

Once the response has been received, our callback method called displayResponse will be fired, and we can deserialize and begin using the objects:

<script type="text/javascript">
function displayResponse()
{
    if(Ajax.checkReadyState(’loading’) == "OK")
    {
       var Auto = Ajax.request.responseText.parseJSON();
       document.getElementById("body").innerHTML += "<br/><b>Remote JSON unserialized</b>";
       document.getElementById("body").innerHTML += "<br/>Car color: "+Auto.Car.color;
       document.getElementById("body").innerHTML += "<br/>Wheel color: "+Auto.Car.Wheel.color;
    }
}
</script>

This is the exciting part! Once we have the responseText, we can simply use the parseJSON method from the JSON parser to reconstruct our Auto object from the serialized data. With this new Auto object, we can make calls to the child objects just as we would otherwise. This feature allows us to send objects back and forth between the server and the client—without having to do a lot of parsing, as we would with a standard XML response. Therefore, we can create client-side JavaScript objects that retain their state via AJAX. The possibilities are endless.

  • + Share This
  • 🔖 Save To Your Account