Throughout this example it is assumed that the 'root' object that is being serialized to JSON is an instance of the following class :
public class MyJson {
}
Example 1 :
An example of an instance of MyJson
, as is:
{}
i.e. since the class has no fields, only curly brackets are serialized. Curly brackets are the common delimiters to represent an object. Notice also how the root object is not serialized as a key-value pair. This is also true for simple types (String, numbers, arrays) when they are not fields of an (outer) object.
Example 2 :
Let's add some fields to MyJson
, and initialize them with some values:
// another class, useful to show how objects are serialized when inside other objects
public class MyOtherJson {}
// an enriched version of our test class
public class MyJson {
String myString = "my string";
int myInt = 5;
double[] myArrayOfDoubles = new double[] { 3.14, 2.72 };
MyOtherJson objectInObject = new MyOtherJson();
}
This is the related JSON representation:
{
"myString" : "my string",
"myInt" : 5,
"myArrayOfDoubles" : [ 3.14, 2.72 ],
"objectInObject" : {}
}
Notice how all the fields are serialized in a key-value structure, where the key is the name of the field holding the value. The common delimiters for arrays are square brackets. Notice also that each key-value pair is followed by a comma, except for the last pair.