Widely hailed as the successor to XML in the browser, JSON aspires to be nothing more than a simple and elegant data format for the exchange of information between the browser and server. In this example we will learn how to create a JSON object on the client using JavaScript (and Prototype), and how to process that same JSON object on the server using Java. The examples use the Google JSON (or GSON) libraries for the JSON parsing.
In the JSP, we setup a hidden form field to hold our JSON string:
<script type="text/javascript"> <!-- var contactTypesList = new Array(); //--> </script> <form> <!-- other page stuff omitted --> <input type="hidden" name='JSONStr' id='JSONStr' value=""> </form>
In our JavaScript code, we are going to do a couple of things. First of all, we are going to check a select list to find the contact that was selected. Next, we create a JSON object called ‘jsonRaContact’. Here’s the JavaScript function:
var allContacts = new Array(); function associateContact(){ var contacts = $('Contacts'); //only run if something was selected if (contacts.selectedIndex >= 0) { var selectedContact = contacts.options[contacts.selectedIndex]; var myCode = $('MyCode').value; var jsonContact = { ltContactType : { contactType : 1 }, contact: { contactId : Number(selectedContact.id) }, myCode : myCode }; allContacts.push(jsonContact); } }
Note that the jsonContact object contains 3 fields, each of which is set in a different way to illustrate the different ways that you can set property values of a JSON object:
- ltContactType, which also contains a property called contactType. This is set by hardcoding a numeric value (obviously not recommended, but shown for illustration).
- contact, which also contains a property called contactId . This is set by creating a new Number object and passing an argument that is the value of a form field.
- myCode, which is set to the value of a form field.
Now we have created a JSON object and added it to an array. The last thing to do when submitting the form is to convert the array of objects to a JSON string, and set a form field value to that string. Here’s the JavaScript code:
$('JSONStr').value = allContacts.toJSON();
The next piece of the puzzle is to deserialize this object in our Java code. We need to import the Google JSON (aka GSON) libraries:
import com.google.gson.Gson; import com.google.gson.JsonObject;
The code to deserialize the JSON object is straightforward. Remember that we passed an array of Contact objects, so that is what we will have after deserialization. Note the class name is an array. Here’s the code:
String jsonStr = (String) request.getParameter("JSONStr"); Gson gson = new Gson(); Contact[] allMyContacts = gson.fromJson(jsonStr, Contact[].class);
Happy coding!
Tags: Java, JavaScript, Prototype