JSON is one of the most popular formats for representing data as text. For example, JSON is used to transfer data between the frontend and backend, in configuration files, in games, in text editors, and in many other areas. As a programmer, you will definitely encounter JSON.

Introducing the syntax

Let's list the data types available in JSON:

  1. Strings are any characters enclosed in double quotes:

    "kwerty"
    "125 + 42"
    "G"

    Special characters are escaped with a slash:

    "first line\nsecond line"
    "He said, \"Hello!\""
  2. Numbers, including negative and real numbers. No quotes:

    18 -333 17.88 1.2e6
  3. The Boolean values are true / false (no quotes).

  4. null is the standard value to represent "nothing". No quotation marks are used here.

  5. Array − This type can contain values of any other types. It is wrapped in square brackets. Its elements are separated by commas:

    ["Code", "Gym", "CodeGym", "¯\_(ツ)_/¯"]
    [true, true, false, true, false, false, false, false, false]
    [[1, 2], [3, 999, 4, -5], [77]]

    The last example is an array of arrays

  6. Object — This complex type is the most commonly used. It contains key-value pairs, where the value can be any of the types listed above, as well as other objects. It is wrapped in curly braces, and the pairs are separated by commas:

    
    {
     "name": "Dale",
     "age": 7
    }
    

Representing a Java object as JSON

Now let's take some Java object and see what it looks like as JSON.

First, let's define a class:


public class Human {
	String name;
	boolean male;
	int age;
	Set<Human> parents;

	public Human(String name, boolean male, int age) {
    	    this.name = name;
    	    this.male = male;
    	    this.age = age;
	}
}

Now let's create our object:


	Human father = new Human("Peter", true, 31);
	Human mother = new Human("Mary", false, 28);
	mother.parents = new HashSet<>();
	Human son = new Human("Paul", true, 7);
	son.parents = Set.of(father, mother);

And now let's try to represent the son object as accurately as possible in JSON format:

{
 "name" : "Paul",
 "male" : true,
 "age" : 7,
 "parents" : [
 {
   "name" : "Peter",
   "male" : true,
   "age" : 31,
   "parents" : null
 },
 {
   "name" : "Maria",
   "male" : false,
   "age" : 28,
   "parents" : null
 }
]
}

Comments in JSON

Everything here is exactly the same as in Java. There are two types of comments: // and /*...*/. I hope I don't need to remind you how they differ?