Just like XML, JSON is also a human-readable Data Interchange Format that is lightweight. It stands for JavaScript Object Notation. This is becoming a popular format generated and parsed by modern web applications. In this recipe, you will see how you can write JSON files.
- Create a method named
writeJson(String outFileName)
that takes the name of the JSON file we will be generating as output with the JSON information in this recipe. - Create a JSON object and use the object's
put()
method to populate a few fields. For instance, say your fields will be books and their authors. The following code will be creating a JSON object and populate a book name from the Harry Potter series and its author's name: JSONObject obj = new JSONObject();
obj.put("book", "Harry Potter and the Philosopher's Stone");
obj.put("author", "J. K. Rowling");
- Next, say that we have three reviewer comments for this book. They can be put together in a JSON array. The array can be populated as follows. First, we use
add()
of the array object to add the reviews. When all the reviews are added to the array, we will be putting the array to the JSON object we created in the previous step:JSONArray list = new JSONArray();
list.add("There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione");
list.add("Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.");
list.add("Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. ");
obj.put("messages", list);
- We will be writing down the information in the JSON object to an output file because this file will be used to demonstrate how we can read/parse a JSON file. The following
try...catch
code blocks write down the information to a JSON file: try {
FileWriter file = new FileWriter("c:test.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
//your message for exception goes here.
}
- The content of the JSON object can also be displayed on the standard output as follows:
System.out.print(obj);
- Finally, close the method:
}
The entire class, the method described in this recipe, and the driver method to call the method with an output JSON file name are as follows:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonWriting {
public static void main(String[] args) {
JsonWriting jsonWriting = new JsonWriting();
jsonWriting.writeJson("C:/testJSON.json");
}
public void writeJson(String outFileName){
JSONObject obj = new JSONObject();
obj.put("book", "Harry Potter and the Philosopher's Stone");
obj.put("author", "J. K. Rowling");
JSONArray list = new JSONArray();
list.add("There are characters in this book that will remind us
of all the people we have met. Everybody knows or knew a
spoilt, overweight boy like Dudley or a bossy and interfering
(yet kind-hearted) girl like Hermione");
list.add("Hogwarts is a truly magical place, not only in the most
obvious way but also in all the detail that the author has gone
to describe it so vibrantly.");
list.add("Parents need to know that this thrill-a-minute story,
the first in the Harry Potter series, respects kids'
intelligence and motivates them to tackle its greater length
and complexity, play imaginative games, and try to solve
its logic puzzles. ");
obj.put("messages", list);
try {
FileWriter file = new FileWriter(outFileName);
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
The output file will be containing data as follows. Note that the output shown here has been modified to increase readability, and the actual output is one, big, flat piece of text:
{
"author":"J. K. Rowling",
"book":"Harry Potter and the Philosopher's Stone",
"messages":[
"There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione",
"Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.",
"Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles."
]
}