Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

JSON with JAVA – Introduction to JSON – Part2

JAVA SE does not have any internal package for processing JSON data. We have to import an external library. There are many libraries available. You can choose any. I will use Json-simple1.1 here. This makes our first step, importing the lib.

Importing the lib

 Click here and download the zip file containing the jar library and follow the following steps to import it into eclipse.
1. Extract the zip file.
2. Right Click on the project folder in the package explorer, hover over Build Path and click on Configure Build Path.
3. You will see a nice window. Go to the Libraries tab and click on Add External JARs.
4. Navigate to the extracted jar folder, select the library and press open/ok.
5. Press ok again and you are done.

Exploring the lib

The library contains parser and data structures to process the given JSON formatted string. The parser parses the JSON data from string/Reader to its own readable form. The data structures consist of JSONObject and JSONArray Classes which store JSON Objects and JSON Arrays respectively. The library has a bunch of other classes and methods but we will confine ourselves to only these three classes (JSONParser, JSONObject, JSONArray). Within these classes, we will use few methods. Why? Because it is just to get you started with JSON. Ok, Whatever. Let’s get started.



public JSONParser()

Public methods

public Object parse (Reader);
public  Object parse (String);
public Object parse (Reader, ContainerFactory);
public Object parse (Reader, ContainerHandler);
public Object parse (String, ContainerFactory);
public Object parse (String, ContainerHandler);
public Object parse (Reader, ContainerHandler, Boolean);
public Object parse (String, ContainerHandler, Boolean);
Above mentioned methods do the same work with different approaches. We will use parse (String) in our code just to make it work easily.

JSONObject and JSONObject

We will initialize these two classes from the JSONParser object and use their following methods:
public Object get (Object); // to read
public Object put (Object, Object); // to write to a JSON object
public boolean add (Object) // to write a single entry at the end of a JSON array
public Boolean add (int, Object) // to write a single entry at int index of a JSON array
public Boolean addAll (Collection) // to write a collection of entries to a JSON array
public Boolean addAll (int, Collection) // to write a collection of entries at int index of a JSON array
To read from JSON you should know that the structure you are reading from JSON is whether a JSONObject or JSONArray and what is its name or index. We will have to pass this information in the get method.

Writing Code

Reading from JSON file “example.json”

  • Preparing the file to read from

File file = new File("example.json");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String jsonString = "";

while (bfr.ready()) {
jsonString += bfr.readLine();

  • Initializing parser

JSONParser parser = new JSONParser();

  • Obtaining the root element

JSONObject rootObject = (JSONObject) parser.parse(jsonString); // we know that the root element of our file is a JSON Object that why parsing the result to JSONObject

  • Getting the hobbies Object

JSONArray hobbies = (JSONArray) rootObject.get("hobbies");

  • Extracting the favorite books array

JSONArray favBooks = (JSONArray) rootObject.get("fav_books");

  • Traversing the JSONArray

for (int i = 0; i < favBooks.size(); i++) {
JSONObject favBook = (JSONObject) favBooks.get(i);
System.out.println(favBook.get("name") + " by " + favBook.get("author"));

Get the full source code here.

Writing to JSON file “example2.json”

  • Getting the file ready to write

FileWriter fwriter = new FileWriter(new File("example2.json"));
BufferedWriter bfwriter = new BufferedWriter(fwriter);

  • Initializing and populating ArrayList

ArrayList<String> fruits = new ArrayList<String>(); // Collection of entries
fruits.add("Apple"); // populating collection

  • Initializing JSONObject and JSONArray

JSONArray jArray = new JSONArray();
JSONObject jObject = new JSONObject();

  • Populating the objects

jArray.addAll(fruits); // collection added to json array
jArray.add(0, "Srawberry"); // a single entry added at 0 index

jObject.put("fruits", jArray); // JSON array added to JSON object

  • writing to file


Get the full source project here.

Give us your feedback by commenting and by participating in the survey. You are doing great, keep it up, see you in the next post.

Introduction to JSON – Part 1

JSON is a data interchange format, frequently used for data exchange between clients and servers across the web. I am dividing this short tutorial series into three parts just to make it easy for you to understand. Part 1 is an introduction to JSON. It shows what is JSON, its structures are and how to write a JSON document. Part 2 explains How to process JSON in JAVA. The last part includes JSON Serialization. Hold your breath, a lot is coming up.
JSON, short for JavaScript Object Notation is a lightweight format which makes data exchange more than easier. It is also used to store data. JSON is language independent. For example, you can make a JSON Object in java and send it to a C# program which will gracefully handle it. JavaScript object can be converted into a JSON object and vice versa.
A JSON document can have two structures.

  • JSON Object: A name value pair or a key value pair. Names/Keys are only strings however values are of various types. Name and value are separated by a single colon (:). JSON Object is contained within the curly braces.

Name : Value,

  • JSON Array: An ordered sequence of values stored in square braces separated by a comma.

Types of Values: These types should be familiar to you and may not need any explanation. A value can be a

  1. String
  2. Number
  3. Bool (True/False)
  4. JSON Object
  5. JSON Array

A JSON value can also be null.
The file which contains JSON data is stored with .json extension. Following is an example document named Example.json. Study it and identify different structures and value types.
Example: Example.json
"first_name": "Salman",
"last_name": "Ahmad",
"gender": "male",
"age": 22,
"hobbies": [
"video games",
"fav_books": [
"name": "The Shallows",
"author": "Nicholas G. Carr"
"name": "Brain Bugs",
"author": "Dean Buonomano"
Next is How to process JSON data in JAVA. We will use this example in our code. See you there.

Inheritance In JAVA: Example

img: Inheritance In JAVA: Example
This is the second last section of the topic Inheritance In OOP where we will study some code snippets. This study will clarify the idea of how to achieve inheritance in JAVA and how it actually works. Without wasting any time and giving length to the post for no reason, let’s start rolling.
Prerequisites: To understand these snippets you should already know what inheritance is. If you don’t, don’t worry. I have a blog post, go here.
Overview: I have written a program named Example which depicts real life inheritance properties like a relationship between child and parent, child access to parent properties etc. The program consists of 4 very simple java classes which are extremely easy to understand. However, if you face any issue ping me in comments. I am always there for you. ExampleBobJohn, and Stephen. The bold faced letters are not names of some persons, in fact, these are names of classes which we are going to study here.
In Java, to establish a child parent relation between two classes, the keyword extends is used at the class declaration time. The child class name is written at the left of the keyword and the parent class name is written on the right side. Syntax:
Child_Class_Name extends Parent_Class_Name
Let’s cast a glance over the access modifiers.
Public: members specified with the public keyword are accessible anywhere in the program using the class object.
Protected: Members modified by protected keyword are accessible within its own class and the child classes without using any object of the parent class.
Privateprivate members are available within the scope of only its own class.
public class Stephen {
protected int money = 5000;

This is the simplest and easiest class I think I have ever seen. As you can see, it only has a single integer data member named money which is initiated to 5000. This class does not extend any class it means that it does not have any parent class. In our story context, Stephen is the grandfather of Bob and have $5000 in his bank account. The variable money is qualified by the keyword protected which means that this variable is accessible in this class and its child classes only. It (variable money) is inaccessible by the object (Object of Stephen Class). Simple.
public class Bob extends Stephen{
protected String eyeColor = "green";
protected String car = "Bob's BMW";

private String mailbox = "Bob's Mailbox";
public void drive() {
System.out.println("Bob is driving: " + car);
public void eyeColor() {
System.out.println("Bob's EyeColor: " + eyeColor);
public void money() {
System.out.println("Bob says: my dad have $" + money);

Bob class extends Stephen class (Bob is a child of Stephen). It has two protected String variables, eyeColor and car and one private String variable, mailbox. What does it show? It shows that the child classes can have or use the eyeColor and car properties while they can't use the mailbox variable. In real life, a child can inherit eye color from his/her parent and can also use their parent’s car but they can’t read their parent’s mailbox unless they are allowed to. While writing this example, I tried to be as real as I could because I think it makes it easier to understand. There are three simple public functions which are accessible through the class object. These functions are self-explanatory.
public class John extends Bob{
public void eyeColor() {
System.out.println("John's eyecolor: " + eyeColor); // note the eyeColor is from 'Bob' Class
public void drive() {
System.out.println("John is driving: " + car); // car is also from Bob class
public void money() {
System.out.println("John says: My grandpa have $" + money); // money is from Stephen class

Class John has nothing more than three functions which simply prints some string with some variables (eyeColor, car, money) from its parent classes. You can see that John is a child of Bob and can access private and public members of Bob class. However, it is using money variable from Stephen class which it does not extends. What the heck is this? Is this correct? Well, yeah! It is correct. The thing is John extends Bob and Bob extends Stephen class so John is also a child of Stephen. Kind of grandchild. This is called multi-level inheritance.
public class Example {
public static void main(String[] args) {
Bob bob = new Bob();
John john = new John();;

Bob is driving: Bob's BMW
Bob's EyeColor: green
Bob says: my dad have $5000
John is driving: Bob's BMW
John's eyecolor: green
John says: My grandpa have $5000

This is the final main class which includes the main function. It simply creates objects of Bob and John classes and calls some of their public functions. Easy. Look at the output and figure out how does it works. It is your home task. If you find yourself in trouble, contact me via comments below.
In coming section, we will discuss why did we study inheritance? And where to use it.  Subscribe using the subscribe button up there in the toolbar and we will notify you when the post is ready. If you have any questions or suggestions, please leave in the comments below and also mark one of the options in the survey popup. 
Stay tuned.