Skip to main content

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.
step2-img
3. You will see a nice window. Go to the Libraries tab and click on Add External JARs.
step3-img
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.

 JSONParser

Constructor

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
fruits.add("Orange");
fruits.add("Peach");

  • 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

bfwriter.write(jObject.toJSONString());

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.

Comments

  1. The particular selection includes parser and also info constructions to be able to method the particular offered JSON formatted stringed. The particular parser parses the particular JSON info coming from string/Reader to be able to a unique legible kind. The info Digital Ocean vs Aws constructions include JSONObject and also JSONArray Lessons which usually retailer JSON Things and also JSON Arrays respectively.

    ReplyDelete

Post a comment

Popular posts from this blog

Introduction to Data Science: What is Big Data?

What Is Big Data First, we will discuss how big data is evaluated step by step process. Evolution of Data How the data evolved and how the big data came. Nowadays the data have been evaluated from different sources like the evolution of technology, IoT(Internet of Things), Social media like Facebook, Instagram, Twitter, YouTube, many other sources the data has been created day by day. 1. Evolution of  Technology We will see how technology is evolved as we see from the below image at the earlier stages we have the landline phone but now we have smartphones of Android, IoS, and HongMeng Os (Huawei)  that are making our life smarter as well as our phone smarter. Apart from that, we have heavily built a desktop for processing of Mb's data that we were using a floppy you will remember how much data it can be stored after that hard disk has been introduced which can stored data in Tb. Now due to modern technology, we can be stored data in the cloud as well. Similarly, nowadays we noticed …

How Big Data Analytics Can Help You Improve And Grow Your Business?

Big Data Analytics There are certain problems that can only solve through big data. Here we discuss the field big data as "Big Data Analytics". The big data came into the picture we never thought how commodity hardware is used to store and manage the data which is reliable and feasible as compared to the costly sources. Now let us discuss a few examples of how big data analytics is useful nowadays. When you go to websites like Amazon, Youtube, Netflix, and any other websites actually they will provide some field in which recommend some product, videos, movies, and some songs for you. What do you think about how they do it? Basically what kind of data they generated on these kind websites. They make sure to analyze properly. The data generated is not small it is actually big data. Now they analysis these big data they make sure whatever you like and whatever you are the preferences accordingly they generate recommendations for you. If you go to Youtube you have noticed it kn…

AI Vs Machine Learning Vs Deep Learning

AI Vs Machine Learning Vs Deep Learning Artificial intelligence, deep learning and machine learning are often confused with each other. These terms are used interchangeably but do they do not refer to the same thing. These terms are closely related to each other which makes it difficult for beginners to spot differences among them. The reason I think of this puzzle is that AI is classified in many ways. It is divided into subfields with respect to the tasks AI is used for such as computer vision, natural language processing, forecasting and prediction, with respect to the type of approach used for learning and the type of data used. Subfields of Artificial Intelligence have much in common which makes it difficult for beginners to clearly differentiate among these areas. Different approaches of AI can process similar data to perform similar tasks. For example Deep learning and SVM both could be used for object detection task. Both have pros and cons. In some cases Machine Learning is …