How do I convert Map to JSON and vice versa using Jackson?

In the following code snippet we will convert java.util.Map object into JSON string and convert back the JSON string into Java Map object. In this example we will be using the Jackson library.

To convert from Map to JSON string the steps are:

  • Create a map of string keys and values.
  • Create an instance of Jackson ObjectMapper.
  • To convert map to JSON string we call the writeValueAsString() method and pass the map as argument.
// Converting Map to JSON
String json = null;
try {
    json = mapper.writeValueAsString(colours);
    System.out.println("json = " + json);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

Now, to convert from JSON string back to map we can do it in the following steps:

  • Create a JSON string, in this case we use the one converted from the colours map.
  • Create an instance of Jackson ObjectMapper.
  • Call the mapper’s readValue() method with JSON string and an empty instance of TypeReference as arguments.
// Converting JSON to MAP
try {
    Map<String, String> newColours =
            mapper.readValue(json, new TypeReference<>() {});
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

And here is the complete code snippet.

package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class MapToJson {
    public static void main(String[] args) {
        Map<String, String> colours = new HashMap<>();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        ObjectMapper mapper = new ObjectMapper();

        // Converting Map to JSON
        String json = null;
        try {
            json = mapper.writeValueAsString(colours);
            System.out.println("json = " + json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        // Converting JSON to MAP
        try {
            Map<String, String> newColours =
                    mapper.readValue(json, new TypeReference<>() {});
            System.out.println("Map:");
            for (var entry : newColours.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Running the code snippet above will print the following output:

json = {"RED":"#FF0000","WHITE":"#FFFFFF","BLUE":"#0000FF","BLACK":"#000000","YELLOW":"#FFFF00","GREEN":"#008000"}
Map:
RED = #FF0000
WHITE = #FFFFFF
BLUE = #0000FF
BLACK = #000000
YELLOW = #FFFF00
GREEN = #008000

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I find Java version?

The simplest way to get the Java version is by running the java -version command in your terminal application or Windows command prompt. If Java is installed and available on your path you can get information like below.

java -version                                     
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)                       
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

Using System Properties

But if you want to get Java version from your Java class or application you can obtain the Java version by calling the System.getProperty() method and provide the property key as argument. Here are some property keys that related to Java version that you can read from the system properties.

package org.kodejava.lang;

public class JavaVersion {
    public static void main(String[] args) {
        String version = System.getProperty("java.version");
        String versionDate = System.getProperty("java.version.date");
        String runtimeVersion = System.getProperty("java.runtime.version");
        String vmVersion = System.getProperty("java.vm.version");
        String classVersion = System.getProperty("java.class.version");
        String specificationVersion = System.getProperty("java.specification.version");
        String vmSpecificationVersion = System.getProperty("java.vm.specification.version");

        System.out.println("java.version: " + version);
        System.out.println("java.version.date: " + versionDate);
        System.out.println("java.runtime.version: " + runtimeVersion);
        System.out.println("java.vm.version: " + vmVersion);
        System.out.println("java.class.version: " + classVersion);
        System.out.println("java.specification.version: " + specificationVersion);
        System.out.println("java.vm.specification.version: " + vmSpecificationVersion);
    }
}

Running the code above give you output like the following:

java.version: 17
java.version.date: 2021-09-14
java.runtime.version: 17+35-LTS-2724
java.vm.version: 17+35-LTS-2724
java.class.version: 61.0
java.specification.version: 17
java.vm.specification.version: 17

Using Runtime.version()

Since JDK 9 we can use Runtime.version() to get Java runtime version. The feature(), interim(), update and patch() methods of the Runtime.Version class are added in JDK 10. These methods is a replacement for the major(), minor() and security() methods of JDK 9.

Below is the code snippet that demonstrate the Runtime.version().

package org.kodejava.lang;

public class RuntimeVersion {
    public static void main(String[] args) {
        System.out.println("Version: " + Runtime.version());
        System.out.println("Feature: " + Runtime.version().feature());
        System.out.println("Interim: " + Runtime.version().interim());
        System.out.println("Update: " + Runtime.version().update());
        System.out.println("Patch: " + Runtime.version().patch());
        System.out.println("Pre: " + Runtime.version().pre().orElse(""));
        System.out.println("Build: " + Runtime.version().build().orElse(null));
        System.out.println("Optional: " + Runtime.version().optional().orElse(""));
    }
}

Running the code snippet above produce the following output:

Version: 17+35-LTS-2724
Feature: 17
Interim: 0
Update: 0
Patch: 0
Pre: 
Build: 35
Optional: LTS-2724

Here are the summary of outputs running the above code using some JDKs installed on my machine.

Version Feature Interim Update Patch Pre Build Optional
10.0.2+13 10 0 2 0 13
11.0.6+8-LTS 11 0 6 0 8 LTS
12.0.2+10 12 0 2 0 10
13.0.2+8 13 0 2 0 8
14+36-1461 14 0 0 0 36 1461
15.0.2+7-27 15 0 2 0 7 27
17+35-LTS-2724 17 0 0 0 35 LTS-2724

How do I convert CSV to JSON string using Jackson?

In the following code snippet we will convert CSV into JSON string using Jackson JSON library. A comma-separated values is a delimited text, it uses comma to separate values. It starts with header on the first line, that will be the JSON key. Each subsequence lines is the data of the csv, which also contains several values separated by comma.

Let’s see the code how to do this in Jackson.

package org.kodejava.jackson;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class CsvToJson {
    public static void main(String[] args) {
        // Comma delimited text created using text blocks
        String countries = """
                ISO, CODE, NAME\s
                CZE, CZ, Czech Republic\s
                DNK, DK, Denmark\s
                DJI, DJ, Djibouti\s
                DMA, DM, Dominica\s
                ECU, EC, Ecuador
                """;

        CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
        CsvMapper csvMapper = new CsvMapper();

        try {
            List<Map<?, ?>> list;
            try (MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader()
                    .forType(Map.class)
                    .with(csvSchema)
                    .readValues(countries)) {
                list = mappingIterator.readAll();
            }

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonPretty = objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(list);
            System.out.println(jsonPretty);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here are the explanation of the code above:

  • Define a csv string, in this case we have a list of countries.
  • Create an empty schema of CsvSchema to process csv with header line.
  • Create an instance of CsvMapper, a specialized type of ObjectMapper.
  • Read and parse csv values into List<Map<?, ?>>.
  • We use the ObjectMapper create a pretty-printed JSON from the list object.

Running the code produces the following output:

[ {
  "ISO" : "CZE",
  "CODE" : " CZ",
  "NAME" : " Czech Republic "
}, {
  "ISO" : "DNK",
  "CODE" : " DK",
  "NAME" : " Denmark "
}, {
  "ISO" : "DJI",
  "CODE" : " DJ",
  "NAME" : " Djibouti "
}, {
  "ISO" : "DMA",
  "CODE" : " DM",
  "NAME" : " Dominica "
}, {
  "ISO" : "ECU",
  "CODE" : " EC",
  "NAME" : " Ecuador"
} ]

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-csv</artifactId>
        <version>2.15.2</version>
    </dependency>    
</dependencies>

Maven Central Maven Central Maven Central Maven Central

How do I convert CSV file to or from JSON file?

In the following code snippet you will see how to convert a CSV file into JSON file and vice versa. We use the JSON-Java library CDL class to convert between CSV and JSON format. The CDL class provide the toJSONArray(String) and toString(JSONArray) methods that allows us to do the conversion between data format.

In the CSV file, the first line in the file will be used as the keys to the generated JSON string. On the other way around, the JSON string keys will be written on the first line of the CSV file as the column header.

Convert CSV file to JSON file.

package org.kodejava.json;

import org.json.CDL;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.stream.Collectors;

public class CsvFileToJsonFile {
    public static void main(String[] args) {
        // Read csv data file and store it in a string
        InputStream is = CsvFileToJsonFile.class.getResourceAsStream("/data.csv");
        String csv = new BufferedReader(
                new InputStreamReader(Objects.requireNonNull(is), StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));

        try {
            // Convert csv text to JSON string, and save it 
            // to a data.json file.
            String json = CDL.toJSONArray(csv).toString(2);
            Files.write(Path.of("data.json"), json.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What we do in the snippet above:

  • Get cvs data as InputStream from the resources directory.
  • We use the BufferedReader and InputStreamReader to iterate and read the InputStream and return it as a string.
  • Convert the csv string into JSON string using CDL.toJSONArray().
  • We can pretty-printed the JSON string by specifying an indentFactor to the toString() method of the JSONArray object.
  • Write the JSON string to a file.

Here is the data.csv file example.

id,first_name,last_name,email,gender,ip_address
1,Abe,Foord,afoord0@harvard.edu,Female,81.38.18.88
2,Editha,Castagnaro,ecastagnaro1@nih.gov,Genderqueer,181.63.39.199
3,Tildie,Furminger,tfurminger2@hud.gov,Male,0.199.18.3

Convert JSON file to CSV file.

package org.kodejava.json;

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

public class JsonFileToCsvFile {
    public static void main(String[] args) {
        // Get data.json resource as InputStream, create JSONTokener
        // and convert the tokener into JSONArray object.
        InputStream is = JsonFileToCsvFile.class.getResourceAsStream("/data.json");
        JSONTokener tokener = new JSONTokener(Objects.requireNonNull(is));
        JSONArray jsonArray = new JSONArray(tokener);

        try {
            // Convert JSONArray into csv and save to file
            String csv = CDL.toString(jsonArray);
            Files.write(Path.of("data.csv"), csv.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What we do in the code snippet above:

  • Get data.json from the resources directory as InputStream.
  • Create a JSONTokener and provide the InputStream as argument to its constructor.
  • Create a JSONArray and pass the JSONTokener object as the constructor argument.
  • Using CDL.toString() we convert the JSONArray object to csv text.
  • Finally, save the csv into file using Files.write().

And here is the data.json JSON file example.

[
  {
    "id": "1",
    "first_name": "Abe",
    "last_name": "Foord",
    "email": "afoord0@harvard.edu",
    "gender": "Female",
    "ip_address": "81.38.18.88"
  },
  {
    "id": "2",
    "first_name": "Editha",
    "last_name": "Castagnaro",
    "email": "ecastagnaro1@nih.gov",
    "gender": "Genderqueer",
    "ip_address": "181.63.39.199"
  },
  {
    "id": "3",
    "first_name": "Tildie",
    "last_name": "Furminger",
    "email": "tfurminger2@hud.gov",
    "gender": "Male",
    "ip_address": "0.199.18.3"
  }
]

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I convert CSV into JSON string using JSON-Java?

In this example we convert CSV or CDL into JSON string. We are going to use the JSON-Java CDL (Comma Delimited Text) class. This class provides static methods that will convert a CSV into JSONArray or to convert a JSONArray into comma separated values.

Here are what we do in the code snippet below:

  • Create a comma delimited text. The first line is the headers, this will be the keys in our JSON string. The couples lines is the values. We use the Java text blocks feature to define the string.
  • Create JSONArray object by calling CDL.toJSONArray() static method as pass the comma delimited string as argument.
  • Next we create a JSONArray object, but we separate the header and the body. We do this by calling the CDL.toJSONArray() and provides headers and countries as arguments.
  • Last, we call the CDL.toString() method with JSONArray as argument to convert it to comma delimited text.

Let’s see the code in action.

package org.kodejava.json;

import org.json.CDL;
import org.json.JSONArray;

public class CsvToJson {
    public static void main(String[] args) {
        // Comma delimited text created using text blocks
        String countries = """
                ISO, CODE, NAME\s
                CZE, CZ, CZECH REPUBLIC\s
                DNK, DK, DENMARK\s
                DJI, DJ, DJIBOUTI\s
                DMA, DM, DOMINICA\s
                ECU, EC, ECUADOR
                """;

        // Convert comma delimited text into JSONArray object.
        JSONArray jsonCountries = CDL.toJSONArray(countries);
        System.out.println(jsonCountries.toString(2));

        // Using a separate header and values to create JSONArray
        // from a comma delimited text
        JSONArray header = new JSONArray();
        header.put("ISO");
        header.put("CODE");
        header.put("NAME");

        countries = """
                CZE, CZ, CZECH REPUBLIC\s
                DNK, DK, DENMARK\s
                DJI, DJ, DJIBOUTI\s
                DMA, DM, DOMINICA\s
                ECU, EC, ECUADOR
                """;

        jsonCountries = CDL.toJSONArray(header, countries);
        System.out.println(jsonCountries.toString(2));

        // Convert back from JSONArray to comma delimited text
        countries = CDL.toString(jsonCountries);
        System.out.println(countries);
    }
}

Running the code produces the following results.

To JSON string:

[
  {
    "ISO": "CZE",
    "CODE": "CZ",
    "NAME": "CZECH REPUBLIC"
  },
  {
    "ISO": "DNK",
    "CODE": "DK",
    "NAME": "DENMARK"
  },
  {
    "ISO": "DJI",
    "CODE": "DJ",
    "NAME": "DJIBOUTI"
  },
  {
    "ISO": "DMA",
    "CODE": "DM",
    "NAME": "DOMINICA"
  },
  {
    "ISO": "ECU",
    "CODE": "EC",
    "NAME": "ECUADOR"
  }
]

Back to CSV

ISO,CODE,NAME
CZE,CZ,CZECH REPUBLIC
DNK,DK,DENMARK
DJI,DJ,DJIBOUTI
DMA,DM,DOMINICA
ECU,EC,ECUADOR

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I pretty-print JSON string in Google Gson?

In the following example you’ll see how to format JSON string using the Google Gson library. Here are the steps:

  • We create a Map.
  • Put a couple key-value pairs to it. We put a string, a LocalDate object and an array of String[].
  • Create a Gson object using the GsonBuilder. This allows us to configure the Gson object.
  • We use the setPrettyPrinting() to configure Gson to output pretty print.
  • The registerTypeAdapter() allows us to register custom serializer, in this case we use it to serialize LocalDate object.

Here is our code snippet:

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GsonPrettyPrint {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Duke");
        map.put("address", "Menlo Park");
        map.put("dateOfBirth", LocalDate.of(2000, Month.FEBRUARY, 1));
        map.put("languages", new String[]{"Java", "Kotlin", "JavaScript"});

        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(LocalDate.class, new LocaleDateAdapter())
                .create();
        String json = gson.toJson(map);
        System.out.println(json);
    }

    static class LocaleDateAdapter implements JsonSerializer<LocalDate> {
        @Override
        public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(date.format(DateTimeFormatter.ISO_DATE));
        }
    }
}

Running this code produces the following result:

{
  "address": "Menlo Park",
  "languages": [
    "Java",
    "Kotlin",
    "JavaScript"
  ],
  "name": "Duke",
  "dateOfBirth": "2000-02-01"
}

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Maven Central

How do I pretty print JSON string in JSON-Java?

In JSON-Java we can make a pretty-printed JSON string by specifying an indentFactor to the JSONObject‘s toString() method. The indent factor is the number of spaces to add to each level of indentation.

If indentFactor > 0 and the JSONObject has only one key, the JSON string will be printed a single line, and if the JSONObject has 2 or more keys, the JSON string will be printed in multiple lines.

Let’s create a pretty-printed JSONObject text using the code below.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;

public class PrettyPrintJSON {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        JSONArray courses = new JSONArray(
                new String[]{"Engineering", "Finance"});
        jsonObject.put("courses", courses);

        // Default print without indent factor
        System.out.println(jsonObject);

        // Pretty print with 2 indent factor
        System.out.println(jsonObject.toString(2));
    }
}

Running this code produces the following output:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
{
  "courses": [
    "Engineering",
    "Finance"
  ],
  "name": "Alice",
  "id": 1,
  "age": 20
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I create JSONArray object?

A JSONArray object represent an ordered sequence of values. We use the put() method to add or replace values in the JSONArray object. The value can be of the following types: Boolean, JSONArray, JSONObject, Number, String or the JSONObject.NULL object.

Beside using the put() method we can also create and add data into JSONArray in the following ways:

  • Using constructor to create JSONArray from string wrapped in square bracket [], where the values are separated by comma. JSONException maybe thrown if the string is not a valid JSON string.
  • Creating JSONArray by passing an array as an argument to its constructor, for example an array of String[].
  • Using constructor to create JSONArray from a Collection, such as an ArrayList object.

The following example show you how to create JSONArray object.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CreateJSONArray {
    public static void main(String[] args) {
        // Create JSONArray and put some values
        JSONArray jsonArray = new JSONArray();
        jsonArray.put("Java");
        jsonArray.put("Kotlin");
        jsonArray.put("Go");
        System.out.println(jsonArray);

        // Create JSONArray from a string wrapped in bracket and
        // the values separated by comma. String value can be 
        // quoted with single quote.
        JSONArray colorArray = new JSONArray("[1, 'Apple', 2022-02-07]");
        System.out.println(colorArray);

        // Create JSONArray from an array of String.
        JSONArray stringArray =
                new JSONArray(new String[]{"January", "February", "March"});
        System.out.println(stringArray);

        // Create JSONArray by passing a List to its constructor
        List<String> list = new ArrayList<>();
        list.add("Red");
        list.add("Green");
        list.add("Blue");
        JSONArray listArray = new JSONArray(list);
        System.out.println(listArray);

        // Using for loop to get each value from the array
        for (int i = 0; i < listArray.length(); i++) {
            System.out.println("Color: " + listArray.get(i));
        }

        // Put JSONArray into a JSONObject.
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("colors", listArray);
        System.out.println(jsonObject);
    }
}

Running the code above produces the following result:

["Java","Kotlin","Go"]
[1,"Apple","2022-02-07"]
["January","February","March"]
["Red","Green","Blue"]
Color: Red
Color: Green
Color: Blue
{"colors":["Red","Green","Blue"]}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I read values from JSONObject?

A JSONObject is an unordered collection of key-value pairs. To read values from the JSONObject we can use the get(String key) and opt(String key) methods. These generic methods return an Object, which you can cast to a certain type.

There are also typed get and opt methods to read value in specific type such as getString(), getInt(), getDouble(), optString(), optFloat(), optBigInteger(), optBoolean(), optEnum(), etc. For more detail, you can check the JSONObject API documentation.

The get methods throws JSONException when the key is not found in the JSONObject, while the opt methods does not throw exception but return null, and we can also pass a default value argument that will be returned when the key is not found.

The code below give you a simple example to read values from JSONObject.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ReadJSONValue {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        jsonObject.put("courses",
                new JSONArray(new String[] {"Engineering", "Finance"}));
        System.out.println(jsonObject);

        // Using get() and opt() methods we need to cast
        // the returned value to the type its store.
        long id1 = (long) jsonObject.get("id");
        String name1 = (String) jsonObject.get("name");
        int age1 = (int) jsonObject.get("age");
        JSONArray courses1 = (JSONArray) jsonObject.get("courses");

        // This will throw exception because JSONObject
        // does not have the address key in it.
        String address1;
        try {
            address1 = (String) jsonObject.get("address");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Using opt() method to read address, does not throw
        // exception
        address1 = (String) jsonObject.opt("address");

        System.out.println("id1      = " + id1);
        System.out.println("name1    = " + name1);
        System.out.println("age1     = " + age1);
        System.out.println("address1 = " + address1);
        System.out.println("courses1 = " + courses1);
        System.out.println();

        // Using data type specific get() and opt() methods.
        // We don't have to cast the return from the getXXX()
        // and optXXX() methods.
        long id2 = jsonObject.getLong("id");
        String name2 = jsonObject.getString("name");
        int age2 = jsonObject.optInt("age");

        // Using optString() to read address and provide default
        // value when address is not found.
        String address2 = jsonObject.optString("address", "No Address");
        JSONArray courses2 = jsonObject.optJSONArray("courses");

        System.out.println("id2      = " + id2);
        System.out.println("name2    = " + name2);
        System.out.println("age2     = " + age2);
        System.out.println("address2 = " + address2);
        System.out.println("courses2 = " + courses2);
    }
}

Running this code produces the following results:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
org.json.JSONException: JSONObject["address"] not found.
    at org.json.JSONObject.get(JSONObject.java:580)
    at org.kodejava.json.ReadJSONValue.main(ReadJSONValue.java:28)

id1      = 1
name1    = Alice
age1     = 20
address1 = null
courses1 = ["Engineering","Finance"]

id2      = 1
name2    = Alice
age2     = 20
address2 = No Address
courses2 = ["Engineering","Finance"]

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I convert Java Object to JSON?

To convert Java objects or POJOs (Plain Old Java Objects) to JSON we can use one of JSONObject constructor that takes an object as its argument. In the following example we will convert Student POJO into JSON string. Student class must provide the getter methods, JSONObject creates JSON string by calling these methods.

In this code snippet we do as follows:

  • Creates Student object and set its properties using the setter methods.
  • Create JSONObject called object and use the Student object as argument to its constructor.
  • JSONObject use getter methods to produces JSON string.
  • Call object.toString() method to get the JSON string.
package org.kodejava.json;

import org.json.JSONObject;
import org.kodejava.json.support.Student;

import java.util.Arrays;

public class PojoToJSON {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("Alice");
        student.setAge(20);
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));

        JSONObject object = new JSONObject(student);
        String json = object.toString();
        System.out.println(json);
    }
}

Running this code produces the following result:

{"courses":["Engineering","Finance","Chemistry"],"name":"Alice","id":1,"age":20}

The Student class use in the code above:

package org.kodejava.json.support;

import java.util.List;

public class Student {
    private Long id;
    private String name;
    private int age;
    private List<String> courses;

    // Getters and Setters removed for simplicity
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central