JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Jackson – Java JSON Processor

June 16, 2013 by Suresh Mohan Leave a Comment

JSON stands for Java Script Object Notation. JSON is a format for efficient transfer of data across Platform. To manipulate JSON in Java, we have many processors. One of such JSON processor in Java is Jackson. Jackson is a high performance JSON processor. Reading, Writing and modifying contents is made easy in Java using the Jackson. Jackson provides with classes and methods to perform these operations. There are so many programmers who want to learn and implement a JSON program in Java. This is a step-by-step guide to read from and write into a JSON file from Java using Jackson.

JSON & Jackson

JSON is based on Java Script. JSON works well with objects. These two factors shall be the spear-head for JSON to gain entry in to the web world, where interoperability is the key to sustain. Since it resembles a JavaScript object, we can use functions like eval() to create or parse the JSON values. In the JSON web site, it is claimed that,

JSON is built on two structures,

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence

Reference : http://www.json.org/

The JSON, as it is evolving in to a giant in this new web world, where it is used from simple AJAX response to RESTful web services, we must also look into how the programming languages handle and generate these files. Jackson easily fits into this requirement. Jackson has capability to read and write into a JSON file from Java, and most stunningly it is capable of creating a JSON from a Java object and read a JSON file back into a Java object. Jackson is packaged in to a jar file which contains all necessary data required for using JSON. We shall discuss about a couple of important classes and its methods to write and read a JSON file in Jackson.

How to read a JSON fil?

Reading a JSON file is far simpler in Jackson. All we need is the Jackson-all-1.8.5.jar file. Let us take a simple JSON file as below and see how Jackson processor is able to read from it.

[java]
<strong>CountryFile.json</strong>
{
"Name":"United States of America",
"Capital":"Washington, D.C.",
"States":["California","Maryland","Florida"]
}
[/java]

This JSON has two kinds of data in it. One is a simple data where key values are present and the other is an array data. The Name holds a string value, the Capital holds a string value and the States hold multiple values in it. Let us create a simple Java method named readJSON() to read this file.

In the Jackson library we have a class named as ObjectMapper. This class holds almost all the important methods required for reading and writing a JSON file. This ObjectMapper class has the method readValue(). This method takes various parameters. Typically it takes the file name and the Java collection into which the JSON file must be mapped. Since the data in the JSON are all key value pairs, Map collection would be a better candidate to hold the JSON values in Java, so for this method we shall pass our CountryFile.json as a file and Map.class as our collection. So the code shall look as below.

[java]
ObjectMapper mapper = new ObjectMapper();
Map&lt;String,Object&gt; userData = mapper.readValue(new File("CountryFile.json"), Map.class);
[/java]

As this line executes, the data from the JSON would have been mapped into the userData object. As this is a map, to get the values from it, we can use the entrySet method.

[java]
Set mySet = userData.entrySet();
[/java]

An iterator can be used on this mySet to get each value that is stored inside the file as object which we can use it for processing further.

[java]
for (Iterator iterator = mySet.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);
}
[/java]

Now we have successfully read the values from the JSON file and printed it.

Write a JSON file

Let us try to create and write a JSON file from Java. Since all the data are key value pairs in JSON, we shall have our data in a Map and try to write it. So first we will create a map and populate the data into it.

[java]
Map<String,Object> country = new HashMap<String, Object>();

country.put("Name","United States of America");
country.put("Capital", "Washington, D.C.");

Set states = new HashSet();
states.add("Florida");
states.add("Maryland");
states.add("California");

country.put("States",states);
[/java]

In this above snippet, we have created a Map named country and added values to it. Moreover we have also created a Set named as states and added values to it.

To write a map into file all we require is the ObjectMapper class and the writeValue() method of it. The writeValue() method takes two parameters namely the object that must be written and the name of the file in which the data must be written.

[java]
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("CountryFile.json"), country);
[/java]

On execution the above line we would be getting JSON file created as CountryFile.json and all our data written into it.

It is important to note the all the values in the map was written as key value pair in the JSON file. The value was written as multivalued element in the JSON. This way we can make use of various methods of the Jackson library to create/read different kinds of elements in the JSON file.
So the final output file would look like,
CountryFile.json

[java]
{
"Name":"United States of America",
"Capital":"Washington, D.C.",
"States":["California","Maryland","Florida"]
}
[/java]

Full code

[java]
package demo.jackson;
import java.io.File;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

public class JacksonDemo {

public void writeJSON() throws Exception {

Map&lt;String,Object&gt; country = new HashMap&lt;String, Object&gt;();

country.put("Name","United States of America");
country.put("Capital", "Washington, D.C.");

Set&lt;String&gt; states = new HashSet&lt;String&gt;();
states.add("Florida");
states.add("Maryland");
states.add("California");

country.put("States",states);

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("CountryFile.json"), country);

System.out.println("**success***");
}

public void readJSON() throws Exception {

ObjectMapper mapper = new ObjectMapper();
Map&lt;String,Object&gt; userData =
mapper.readValue(new File("CountryFile.json"), Map.class);

Set mySet = userData.entrySet();

for (Iterator iterator = mySet.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);
}
}

public static void main(String[] args){
try {
JacksonDemo myPgm = new JacksonDemo();
myPgm.writeJSON();
myPgm.readJSON();
} catch (Exception e) {
e.printStackTrace();
}
}
}
[/java]

Conclusion

We have discussed how to read and write JSON from Java using the Jackson processor. Don’t sit back and assume that this is all Jackson can do, we have just now hit the tip of an iceberg, there are lots of things to explore inside the Jackson, which offers multiple varieties to process JSON files.

Filed Under: Java Tagged With: Jackson, JSON

Photo Viewer using JavaScript

April 29, 2013 by Suresh Mohan Leave a Comment

HTML has a separate element for image display. This will display the image in a specific region of the page. If we want to add multiple pictures and view it one at a time, then HTML does not have any such tag. We need to build our own design for that. This is a JavaScript code which will facilitate a new design to display images in a web page.

We have navigation buttons namely back and next to view the various pictures and an exit button to exit this window and view the page.Let us first see how we need to use this java script functionality in the web browser.

[java]
<div id="imageViewer"></div>
<a href="#" onclick="showImage(‘Gallery/Mangalore’,101)">Mangalore</a>
<br/>
<a href="#" onclick="showImage(‘Gallery/Sceneries’,101)">Sceneries</a>
[/java]

First step is that we need to create is a div element. This element must be named as imageViewer. Note that no other name shall be used here, as our script can identify only this name. To specify various links to be used, we can add anchor elements which would invoke the showImage script functions. Two parameters, namely the image folder path and the first image name must be passed. Note that the name of the image can be only numbers between 101 and 999. And the extension of the file must be JPG in caps. For example 104.JPG.

JS_PV

Once this is done, we are done for making our viewer. The photo viewer code looks as below.

[java]
<script type="text/javascript">
imageName=0;
folderName=’empty’;
arrows=true;

function showImage(folder,file) {
imageName=file;
folderName=folder;
displayDivision();
displayImage();
}

function changeImageNext() {
imageName++;
displayImage();
}

function changeImageBack() {
imageName–;
displayImage();
}

function displayDivision() {

if(arrows) {
arrows=false;

//create a outer image division and set its style properties
outerImageDiv = document.createElement(‘DIV’);
outerImageDiv.id=’outerImageDiv’;
outerImageDiv.style.position=’fixed’;
outerImageDiv.style.width=’100%’;
outerImageDiv.style.height=’100%’;
document.getElementById("imageViewer").appendChild(outerImageDiv);

//create a table element and set its style properties
table = document.createElement(‘table’); //table tab
table.id=’imageTable’;
table.align=’center’;
table.frame=’box’;
table.style.backgroundColor=’#F0F0F0′;

//create a table body element
tbody=document.createElement(‘tbody’); //tbody tbo

//create the first row of the table.
firstRow=document.createElement(‘tr’); //row

//create the first cell of first row and align it
firstCellRow1=document.createElement(‘td’); // cell
firstCellRow1.align=’left’;
//populate the elements of the firstCellRow1
backSpan = document.createElement("span");
backSpan.id=’backSpan’;
backSpan.style.border=’1px solid #C8C8C8′;
backSpan.onclick=function() {changeImageBack();};
backSpan.appendChild(document.createTextNode(‘ BACK ‘));
firstCellRow1.appendChild(backSpan);
firstRow.appendChild(firstCellRow1);

//create the second cell of first row and align it
secondCellRow1=document.createElement(‘td’); //cell
secondCellRow1.align=’center’;
//populate the elements of the secondCellRow1
exitSpan = document.createElement("span");
exitSpan.id=’exitSpan’;
exitSpan.style.border=’1px solid #C8C8C8′;
exitSpan.onclick=function() {removeDivision();};
exitSpan.appendChild(document.createTextNode(‘ EXIT ‘));
secondCellRow1.appendChild(exitSpan);
firstRow.appendChild(secondCellRow1);

//create the third cell of first row and align it
thirdCellRow1=document.createElement(‘td’);
thirdCellRow1.align=’right’;
//populate the elements of the thirdCellRow1
nextSpan = document.createElement("span");
nextSpan.id=’nextSpan’;
nextSpan.style.border=’1px solid #C8C8C8′;
nextSpan.onclick=function() {changeImageNext();};
nextSpan.appendChild(document.createTextNode(‘ NEXT ‘));
thirdCellRow1.appendChild(nextSpan);
firstRow.appendChild(thirdCellRow1);

//append the first row in the table body
tbody.appendChild(firstRow);

//create the second row of the table.
secondRow=document.createElement(‘tr’);

//create the first cell of first row, align it and span
firstCellRow2=document.createElement(‘td’);
firstCellRow2.align="center";
firstCellRow2.colSpan=’3′;

//populate the elements of the first cell in row 2

//create and set style for the image division
imageDiv = document.createElement(‘DIV’);
imageDiv.id=’imageDiv’;
imageDiv.style.backgroundColor=’#F0F0F0′;
imageDiv.style.width =’700px’;
imageDiv.style.height =’500px’;

//create and append an image element to the image division
image = document.createElement("IMG");
image.id=’myImages’;
imageDiv.appendChild(image);

firstCellRow2.appendChild(imageDiv);
secondRow.appendChild(firstCellRow2);

//append the second row in the table body
tbody.appendChild(secondRow);

//append the table body in the table
table.appendChild(tbody);

//append the table to the oter image division
document.getElementById(‘outerImageDiv’).appendChild(document.createElement(‘br’));
document.getElementById(‘outerImageDiv’).appendChild(document.createElement(‘br’));
document.getElementById(‘outerImageDiv’).appendChild(table);
}

document.getElementById(‘outerImageDiv’).style.visibility=’visible’;
}

function displayImage() {
//create a new image element and set the style for it
newImage = document.createElement("IMG");
newImage.src =folderName+"/"+imageName+".JPG";
newImage.id=’myImages’;
newImage.style.width = ‘700px’;
newImage.style.height =’500px’;
newImage.onerror=function() {noImagesToDisplay();};

//replace the old image with the new image.
oldImage = document.getElementById(‘myImages’);
document.getElementById(‘imageDiv’).replaceChild(newImage, oldImage);
}

function removeDivision() {
document.getElementById(‘outerImageDiv’).style.visibility=’hidden’;
alert(‘Thanks for viewing’);
}

function noImagesToDisplay() {
document.getElementById(‘outerImageDiv’).style.visibility=’hidden’;
alert(‘no images to display’);
}
</script>
[/java]

Some of the operations that this script supports are next navigation, which takes to the next picture in the folder. back navigation which takes to the previous photo in the folder. The exit will exit from the viewer into the html page. On exit an alert message specifying “thanks for viewing” shall be shown to the user. If there are no more pictures, then “no images to display” alert message shall be displayed to the user.

We are all set. Now try to open the web page in your browser and click on the links. You shall get an amazing new window open in which your image will be displayed. Moreover we also have some navigation features which make our photo viewing experience great.

Filed Under: JavaScript Tagged With: javascript

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved