Reading a JSON and looping on it

I have a JSON array of strings stored in a file, I want to read it from a JavaScript and use in someway its values. To simplify the file access, I am about to use the jQuery getJSON() function.

The JSON file, named numbers.json, contains something like this:
["Zero", "One", "Two", "Three"]

This JavaScript fragment gets asynchronously the file, and then dumps to the console any elements in the fetched JSON:
$.getJSON('numbers.json').done(function(numbers) {
  for(var i=0; i < numbers.length; ++i) {
    console.log(numbers[i]);
  }
});
Calling getJSON() we ask jQuery to fetch the content of the passed filename and, when done, calling the anonymous function passed as parameter to done(), putting in its input parameter, that I named numbers, the contained JSON. In the body of that anonymous function we have to deal with the fetched data. What I do there is simply looping on the array, and logging to the console each component.

Go to the full post

From Java objects to Json

I am pretty busy in these days. Just a few lines to remember to myself that I have a couple of blogs to think about, and it would be good write something on them once in a while.

Currently I am working on a servlet that also generates a few Json responses on request. It happens. Json is much popular in JavaScript environment (and not only there), and one should be prepared to convert data to and from that format.

That servlet I am working on, currently does this job "by hand" (yuck!) polluting the code with obscure short strings that makes a nightmare maintaining it.

A few better solutions exist. I had a fast look around and I picked up the google-gson library, that looks to me simple and powerful enough for my current requirements.

As you could guess from its name, google-gson is a project hosted by Google Code. You would find there its home page. There you could also get the latest version (currently 2.2.2) and enough documentation to start working with it.

I have written a few test cases, just to check it before start using it in the real code, but nothing worth to be written here. Have a look instead to their user guide, that includes a few examples that should be enough to let you see how it works.

Go to the full post