For this homework, you will create a class that outputs various collections as "pretty" JSON objects or arrays to file. Use 2 `` space characters for each level of indentation, the \\n
line separator between elements, and UTF8
when writing your files.
See the Javadoc comments for additional details.
We need a standard output file format for the data calculated by our search engine to debug and test the accuracy of our code. The JSON format (or JavaScript Object Notation) provides a text-based human-readable (and thus debug-friendly) format commonly used by web applications.
<aside> <img src="/icons/git_gray.svg" alt="/icons/git_gray.svg" width="40px" />
This homework assignment is directly useful for your project. Consider copying this class into your project repository when done!
</aside>
For example, a pretty JSON array (used for Java arrays, lists, and sets) looks like:
[
1,
2,
3
]
Note that there is no comma after the last element in the array.
Objects look like:
{
"ant": 1,
"bat": 2,
"cat": 3
}
Note that strings and keys are always in "
quotation marks, but numbers are not.
An object with nested arrays as values looks like:
{
"ant": [
1
],
"bat": [
1,
2
],
"cat": [
1,
2,
3
]
}
The examples here happen to be sorted, but that is not necessary for JSON output.
Below are some hints that may help with this homework assignment:
Eclipse has built-in file comparison functionality. It can show you exactly how your file output differs from the expected output (even if its just a trailing space at the end of a line). See the Comparing Output in Eclipse guide for details.
The general form of each method takes an indentation level, which allows for reusing these methods when creating nested output. The indentation level should be not be applied to the first bracket or brace. Instead, output the inner elements by one more than the provided level, and output the final bracket or brace at the original indentation level.
If you directly call write()
an int
or Integer
, it will often be seen as a character code. For example, 65
is the character code for A
. If you want to actually write the digits 65
to file, convert to a String
object first. For example, try running this:
PrintWriter writer = new PrintWriter(System.out);
Integer i = 65;
writer.write(i);
writer.flush();
Compare that output to:
PrintWriter writer = new PrintWriter(System.out);
Integer i = 65;
writer.write(i.toString());
writer.flush();
Note this is not a problem for most print()
and println()
methods, so it depends on what you use to write to file.