How to write a Json file 6


From time to time I need to save or send Java Objects and the best way to do that is by serializing them into a Json formatted string. The problem is I always forget how they’re formatted even though its so simple. So here’s a few notes, more for myself than anything else, on how to format a Json file.

A Json file/string starts and ends with curly brackets, representing that a Java Class starts and ends there.

{
    
}

Between the curly brackets are the Java class’ fields with the field name in double-quotes on the left, a colon, then the value to assign to it on the right. Values can be numbers, booleans, enums, Strings, and even arrays and other Java class. Booleans are spelled out true and false, numbers are written as normal numbers, and Strings and enums go inside double-quotes.

{
    "number": 1990,
    "boolean": true,
    "text": "This is a string",
    "enum": "Type"
}

Multiple fields within a class are separated by commas. White space in a Json is ignored by the compiler and will only come out of a Json converter if specifically told to ‘prettify’ the output. When the compiler comes to the enum value and the enum field it should know what to do.

Arrays in a Json are represented by open and close square brackets, with the values inside separated by commas.

{
    "arrayA": [ 2, 6, 21, 64, 101, 5 ],
    "arrayB": [
        "Brian",
        "Amy",
        "Heather",
        "Cindy"
    ]
}

Nested classes in a Json are represented by open and close curly brackets and the fields and values are declared in the same way.

{
    "person": {
        "name": "Brian",
        "age": 25,
        "cool": true
    }
}

This notation can also be used to build java.util.Hashmap s and other similar maps and lists.

{
    "people": {
        "Brian": {
            "name": "Brian",
            "age": 25,
            "cool": true
        },
        "Amy": {
            "name": "Amy",
            "age": 23,
            "cool": false
        }
    }
}

Finally you’ll need a Json converter which you’ll use to serialize and deserialize your Jsons and classes. There are a million libraries online for Json converters, the one I really like and use is Google’s Gson, its fast, its easy, I give it an object it gives me a string, and if I give it a string it gives me an object. I’ve used some that wanted you to annotate every last field in your class and that becomes a huge pain. I’ve also heard really good things about Jackson and I’ve been meaning to try it but meh.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on Reddit

Leave a comment

Your email address will not be published. Required fields are marked *

6 thoughts on “How to write a Json file