Convert object to JSON format in Java

In Java, you can use the built-in Gson library to convert an object to JSON format. 

Here is an example:


public class MyClass {
    public static void main(String[] args) {
        // Create an object
        MyObject obj = new MyObject("John", 30);

        // Convert the object to JSON format
        Gson gson = new Gson();
        String json = gson.toJson(obj);

        // Print the JSON string

class MyObject {
    String name;
    int age;

    public MyObject(String name, int age) { = name;
        this.age = age;

In this example, we create a MyObject class with name and age fields. Then we create an instance of MyObject and use the Gson library to convert it to a JSON string. Finally, we print the JSON string to the console.

The output will be:


You can use this method to convert any object to JSON format, as long as the object is serializable (i.e., all of its fields are either primitive types, String, or other serializable objects).