Wednesday 26 December 2012

Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Leave a Comment
Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.

As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.

The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.
Read More...

Thursday 20 December 2012

Can a class (whether an inner or outer class) be declared static?

Leave a Comment
In order to understand the use of the static keyword in class declaration, we need to understand the class declaration itself. You can declare two kinds of classes: top-level classes and inner classes.

Top-level classes

You declare a top-level class at the top level as a member of a package. Each top-level class corresponds to its own java file sporting the same name as the class name.
A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do so. The compiler will detect and report this error.

Inner classes

You define an inner class within a top-level class. Depending on how it is defined, an inner class can be one of the following four types:
1. Anonymous. Anonymous classes are declared and instantiated within the same statement. They do not have names, and they can be instantiated only once.
The following is an example of an anonymous class:

okButton.addActionListener( new ActionListener(){
   public void actionPerformed(ActionEvent e){
      dispose();
   }
});


Because an anonymous class doesn't have a normal class declaration where it's possible to use static, it cannot be declared static.
2. Local. Local classes are the same as local variables, in the sense that they're created and used inside a block. Once you declare a class within a block, it can be instantiated as many times as you wish within that block. Like local variables, local classes aren't allowed to be declared public, protected, private, or static.
Here's a code example:
//some code block .......{
   class ListListener implements ItemListener {
      List list;
      public ListListener(List l) {
         list = l;
      }
      public void itemStateChanged(ItemEvent e) {
         String s = l.getItemSelected();
         doSomething(s);
      }
   }
   List list1 = new List();
   list list2 = new List();
   list1.addItemListener(new ListListener(list1));
   list2.addItemListener(new ListListener(list2));
}


3. Member. Member classes are defined within the body of a class. You can use member classes anywhere within the body of the containing class. You declare member classes when you want to use variables and methods of the containing class without explicit delegation.
The member class is the only class that you can declare static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.
When you declare a member class with a static modifier, it becomes a nested top-level class and can be used as a normal top-level class as explained above.
4. Nested top-level. A nested top-level class is a member classes with a static modifier. A nested top-level class is just like any other top-level class except that it is declared within another class or interface. Nested top-level classes are typically used as a convenient way to group related classes without creating a new package.
Read More...

Tuesday 18 December 2012

Annonymous Inner Classes In Java

Leave a Comment
A class that have no name is called anonymous inner class;

They can be created by using:
1. class
2. abstract class
3. interfaces

Example 1:
lets consider a abstract class

package abstractconcept;
public abstract class MyAbstract
{
   public String name;
   public int age;
 
   /**Abstract Method*/
   public abstract int sum(int a,int b);
 
   /**
    * Concrete Method
    */
   public int sub(int c,int d)
   {
       return c-d;
   }
}




Implementing Class
package abstractconcept;

public class Annonymous
{
  public static void main(String[] args)
  {
   
      MyAbstract obj=new MyAbstract() {
       
        @Override
        public int sum(int a, int b) {
            // TODO Auto-generated method stub
            return a+b;
        }
    };
     System.out.println(obj.sum(10,10));
  }
 
}


Output: 20

Code of Anonymous Class:Generated by the compiler at compile time

import java.io.PrintStream.*;
public class Annonymous$1 extends MyAbstract  

   Annonymous$1(){} //Default Constructor
   public int sum(int a, int b) 
   {
        return a+b;
   }


}

Example 2:
Anonymous inner class using interface

package abstractconcept; 
interface MyAbstract

   /**Abstract Method*/
   public abstract int sum(int a,int b);

}



Implementing Class
package abstractconcept;

public class Annonymous implements
MyAbstract
{
  public static void main(String[] args)
  {
   
      MyAbstract obj=new MyAbstract() {
       
        @Override
        public int sum(int a, int b) {
            // TODO Auto-generated method stub
            return a+b;
        }
    };
     System.out.println(obj.sum(10,10));
  }
 
}


Output: 20

Code of Anonymous Class:Generated by the compiler at compile time

import java.io.PrintStream.*;
public class Annonymous$1 extends MyAbstract  

   Annonymous$1(){} //Default Constructor
   public int sum(int a, int b) 
   {
        return a+b;
   }


}
 

Read More...

Monday 17 December 2012

Password At Command Prompt - console.readPassword()

Leave a Comment
import java.io.*;

class Abc
{
public static void main(String args[])
{
System.out.println("hello");
Console console=System.console();
console.printf("Enter Password\n");

char a[]=console.readPassword();
for(int i=0;i<a.length;i++)
{
console.printf("%c",a[i]);
}
}
}
Read More...

Saturday 15 December 2012

Marker Interface in Java: what, why, uses ?

Leave a Comment
What are Marker Interfaces in Java?

An empty interface having no methods or fields/constants is called a marker interface or a tag interface. This of course means if the interface is extending other interfaces (directly or indirectly) then the super interfaces must not have any inheritable member (method or field/constant) as otherwise the definition of the marker interface (an entirely empty interface) would not be met. Since members of any interface are by default 'public' so all members will be inheritable and hence we can say for an interface to be a marker interface, all of its direct or indirect super interfaces should also be marker. (Thanks marco for raising the point. I thought it was obvious, but mentioning all this explicitly would probably help our readers.)

There are few Java supplied marker interfaces like CloneableSerializable, etc. One can create their own marker interfaces the same way as they create any other interface in Java.

Purpose of having marker interfaces in Java i.e., why to have marker interfaces?

The main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementor of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.

What purpose does the Cloneable interface serve?

When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException. Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation. Cloneable is a marker interface and having no behavior declared in it for the implementing class to define because the behavior is to be supported by JVM and not the implementing classes (maybe because it's too tricky, generic, or low-level at the implementing class level). So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality.

How does JVM support the 'cloning' functionality - probably by using a native method call as cloning mechanism involves some low-level tasks which are probably not possible with using a direct Java method. So, a possible 'Object.clone' implementation would be something like this:-

public Object clone() throws CloneNotSupportedException {

 if (this implements Cloneable)

     return nativeCloneImpl();

 else

     throw new CloneNotSupportedException();

}

Anyone wondered as to why and when do we get 'CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for Cloneable or any other standard marker interface for that matter.


Defining an user-defined marker interface in Java


Let's define a user-defined marker interface. Let's say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines - allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.



public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}

In your reporting modules, you can probably get the segregation using something similar to below:-



for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
}
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
}
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
}
else {
//... handle stats for general items
}
}

As you can see the medicines themselves don't need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.


Now this can be done by having a flag as well... yeah, sure it can be. But, don't you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation - final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.


Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it's not that if you go via public final approach, you can't do that. You can very well do, but casting might look a cleaner approach in many situations.


The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.


Note: Annotations are considered as another possible (quite popular as well) alternative to marker interfaces
Read More...

Does 'static' cause Memory Leak in Java?

Leave a Comment

Does 'static' cause Memory Leak in Java?

What's memory leak? In simple terms, it's unused but referenced (somehow because the programmer probably unintentionally forgot to remove the references once the use of the object was over) part of the memory. Before we start discussing if 'static' can cause memory leak in Java, let me assure you that whatever you've read about Garbage Collectors in Java, is still valid and it certainly takes care of most (almost all) of the memory allocation/reclaimation of Java objects. But, that alone doesn't remove the possibility of the presence of memory leak in a Java program - just for example, you might not only be using only Java objects in your Java program. Putting it differently, what if you have used some native objects and forgot to reclaim the memory explicitly because that's anyway not going to be taken care by the GC (which takes care of heap memory management only)... right?

Now that we agree with the possibility of a Java program having potential memory leaks, let's see if using 'static' can also be one of the potential reasons for memory leaks in Java.

How to find if your Java program contains Memory Leaks?

Well... the programmer should have kept their eyes open while development itself. Once the app is ready, one may like to use Profilers (available from many vendors) to analyze the object graphs.

If your Java app is usually crashing with 'OutOfMemoryError' after executing for a while then it should ring an alarm for the possibility of memory leaks in your app. Though, this doesn't necessarily mean your app is having memory leaks, it might be possible that the allocated heap space is not enough for the proper functioning of your app.

Does 'static' cause memory leak in Java?

'static' can't straightway be blamed for causing memory leaks. But, if the programmer has not well thought the usage and has not taken care of the setting the references to 'null' explicitly after using the static objects then they can definitely cause memory leaks. Let's see how.

As you know 'static' members will by default live for the entire life of an app unless they are explicitly set to 'null'. So, always make it a point to nullify the references as soon as you reach at a point in your code where the use of the static member is over. For example: suppose you have created a 'Statement' object from a DB Connection and the connection is a pooled one. Now as you know calling close()method on a pooled connection will not actually close the connection instead it will return the Connection object to the pool to be re-used. So, in such a case unless you explicitly close the 'Statement' object, it would keep consuming precious memory space for no real use. Just think the scenario where you have declared the 'Statement' object as a static member, it'll be maintained in the memory for the entire life time of the app even when the control is out of the scope. It's just a sample scenario and many of you might never have used 'Statement' object in such an irresponsible manner. It's just an attempt to show how the 'static' can be misused to cause memory leaks in Java.

Not that if your Statement object is non-static you should reply on the out-of-scope nullification (i.e., as soon as control is out of scope the local objects would be marked for re-claimation) as in case you still have a significant amount of code (in terms of time/space) after using the Statement last and before reaching the end of the local scope, it would be a sheer wastage of memory if you don't explicitly nullify the 'Statement' after its use is over. Such a scenario should also be thought of as memory leaks only and one should always make sure the nullification of resources is as close to their last usage as possible.

Therefore, in summary we can say that one should/must :-
  • always think if you really need to make this variable/member a 'static' one?
  • always try to confine the scope of an object to restrict its usage only to the section it's actually needed
  • always make a conscious effort to explicitly nullify objects once you finish using them (especially the large objects)
Read More...

Why String has been made immutable in Java?

Leave a Comment
Though, performance is also a reason (assuming you are already aware of the internal String pool maintained for making sure that the same String object is used more than once without having to create/re-claim it those many times), but the main reason why String has been made immutable in Java is 'Security'. Surprised? Let's understand why.

Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.


As we know the filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.


Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java.
 I understand there are so many 'could have's here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.

With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).
Read More...

clone() how cloning works in Java?

Leave a Comment
What is the role of the clone() method in Java?

protected Object clone() throws CloneNotSupportedException - this method is used to create a copy of an object of a class which implements Cloneableinterface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Cloneable interface
We get CloneNotSupportedException  if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Example: how cloning works in Java?

Class A {
...
}
A objA = new A();
A objACloned = (A) objA.clone();


Now, objA != objACloned - this boolean expression will always be true as in any case a new object reference will be created for the cloned copy.

objA.getClass() == objACloned.getClass() - this boolean expression will also be always true as both the original object and the cloned object are instances of the same class (A in this case).

Initially, objA.equals(objACloned) will return true, but any changes to any primitive data type member of any of the objects will cause the expression to returnfalse. It's interesting to note here that any changes to the members of the object referenced by a member of these objects will not cause the expression to returnfalse. Reason being, both the copies are referring to same object as only the object references get copied and not the object themselves. This type of copy is calledShallow Copy (Read Next - Deep Copy vs Shallow Copy >>  You may browse the links given in that article to go through various aspects of Cloning in Java). This can be understood easily by looking at the following memory diagram:-


 
Read More...

Jackson Tree Model Example

Leave a Comment

In Jackson, you can use “Tree Model” to represent JSON, and perform the read and write operations via “JsonNode“, it is similar to DOM tree for XML. See code snippet :
 ObjectMapper mapper = new ObjectMapper();
 
 BufferedReader fileReader = new BufferedReader(
  new FileReader("c:\\user.json"));
 JsonNode rootNode = mapper.readTree(fileReader);
 
 /*** read value from key "name" ***/
 JsonNode nameNode = rootNode.path("name");
 System.out.println(nameNode.getTextValue());

This time, we show you how to read the JSON string from “file.json” into a “Tree“, and also how to read and and update those values via JsonNode.
File : file.json
{
  "age" : 29,
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "harit"
 }
See full example, it should be self-explanatory.
package com;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
 
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
 
public class JacksonTreeNodeExample {
 public static void main(String[] args) {
 
  ObjectMapper mapper = new ObjectMapper();
 
  try {
 
   BufferedReader fileReader = new BufferedReader(
    new FileReader("c:\\user.json"));
   JsonNode rootNode = mapper.readTree(fileReader);
 
   /*** read ***/
   JsonNode nameNode = rootNode.path("name");
   System.out.println(nameNode.getTextValue());
 
   JsonNode ageNode = rootNode.path("age");
   System.out.println(ageNode.getIntValue());
 
   JsonNode msgNode = rootNode.path("messages");
   Iterator<JsonNode> ite = msgNode.getElements();
 
   while (ite.hasNext()) {
    JsonNode temp = ite.next();
    System.out.println(temp.getTextValue());
 
   }
 
   /*** update ***/
   ((ObjectNode)rootNode).put("nickname", "new nickname");
   ((ObjectNode)rootNode).put("name", "updated name");
   ((ObjectNode)rootNode).remove("age");
 
   mapper.writeValue(new File("c:\\user.json"), rootNode);
 
  } catch (JsonGenerationException e) {
 
   e.printStackTrace();
 
  } catch (JsonMappingException e) {
 
   e.printStackTrace();
 
  } catch (IOException e) {
 
   e.printStackTrace();
 
  }
 
 }
 
}
Output
harit
29
msg 1
msg 2
msg 3
And the file “c:\\file.json” is updated with following new content :
{
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "updated name",
  "nickname" : "new nickname"
}

Read More...

How To Convert Java Map To / From JSON (Jackson)

Leave a Comment

This time, we are doing the same, but replace user define object with Map.
Map is more suitable in a simple and short JSON processing, for complex JSON structure, you should always create an user defined object for easy maintainability.
In this tutorial, we show you how to use Map to construct the JSON data, write it to file. And also how to read JSON from file, and display each value via Map.

1. Write JSON to file

Jackson example to use Map to construct the entire JSON data structure, then write it to file named “user.json“.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
     public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 Map<String, Object> userInMap = new HashMap<String, Object>();
 userInMap.put("name", "harit");
 userInMap.put("age", 29);
 
 List<Object> list = new ArrayList<Object>();
 list.add("msg 1");
 list.add("msg 2");
 list.add("msg 3");
 
 userInMap.put("messages", list);
 
 try {
 
   // write JSON to a file
   mapper.writeValue(new File("c:\\user.json"), userInMap);
 
 } catch (JsonGenerationException e) {
   e.printStackTrace();
 } catch (JsonMappingException e) {
   e.printStackTrace();
 } catch (IOException e) {
   e.printStackTrace();
 }
     }
}
Output – user.json
{
 "age":29,
 "name":"harit",
 "messages":["msg 1","msg 2","msg 3"]
}

2. Read JSON from file

Read JSON data from file, convert it to Map and display the values.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
 
public class JacksonExample {
     public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
    // read JSON from a file
    Map<String, Object> userInMap = mapper.readValue(
  new File("c:\\user.json"), 
  new TypeReference<Map<String, Object>>() {});
 
    System.out.println(userInMap.get("name"));
    System.out.println(userInMap.get("age"));
 
    ArrayList<String> list = 
  (ArrayList<String>) userInMap.get("messages");
 
    for (String msg : list) {
  System.out.println(msg);
    }
 
 } catch (JsonGenerationException e) {
        e.printStackTrace();
 } catch (JsonMappingException e) {
    e.printStackTrace();
 } catch (IOException e) {
    e.printStackTrace();
 }
     }
}
Output
harit
29
msg 1
msg 2
msg 3
Read More...

How To Convert Java Object To / From JSON (Jackson)

3 comments

JSON (JavaScript Object Notation), is a simple and easy to read and write data exchange format. It’s popular and implemented in countless projects worldwide, for those don’t like XML, JSON is a very good alternative solution.
In this series of Java JSON tutorials, we focus on three popular third party Java libraries to process JSON data, which areJacksonGoogle Gson and JSON.simple
For object/json conversion, you need to know following two methods :
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
Note
Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

1. Jackson Dependency

Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion.

2. POJO

An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.
package json;
 
import java.util.ArrayList;
import java.util.List;
 
public class User {
 
 private int age = 29;
 private String name = "harit";
 private List<String> messages = new ArrayList<String>() {
  {
   add("msg 1");
   add("msg 2");
   add("msg 3");
  }
 };
 
 //getter and setter methods
 
 @Override
 public String toString() {
  return "User [age=" + age + ", name=" + name + ", " +
    "messages=" + messages + "]";
 }
}

3. Java Object to JSON

Convert an “user” object into JSON formatted string, and save it into a file “user.json“.
package json;
 
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
 User user = new User();
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
  // convert user object to json string, and save to a file
  mapper.writeValue(new File("c:\\user.json"), user);
 
  // display to console
  System.out.println(mapper.writeValueAsString(user));
 
 } catch (JsonGenerationException e) {
 
  e.printStackTrace();
 
 } catch (JsonMappingException e) {
 
  e.printStackTrace();
 
 } catch (IOException e) {
 
  e.printStackTrace();
 
 }
 
  }
 
}
Output
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"harit"}
Note
Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

4. JSON to Java Object

Read JSON string from file “user.json“, and convert it back to Java object.
package json;
 
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
  // read from file, convert it to user class
  User user = mapper.readValue(new File("c:\\user.json"), User.class);
 
  // display to console
  System.out.println(user);
 
 } catch (JsonGenerationException e) {
 
  e.printStackTrace();
 
 } catch (JsonMappingException e) {
 
  e.printStackTrace();
 
 } catch (IOException e) {
 
  e.printStackTrace();
 
 }
 
  }
 
}
User [age=29, name=harit, messages=[msg 1, msg 2, msg 3]]

Read More...