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