Serialize Object to JSON Example

This program demonstrates serializing a Java object to JSON.

Problem Statement

Write a Java program that serializes a Student object into JSON using Gson library.

Source Code

1 import com.google.gson.Gson;
2 class Student {
3 int id; String name;
4 Student(int id,String name){ this.id=id; this.name=name; }
5 }
6 public class JSONSerializeExample {
7 public static void main(String[] args) {
8 System.out.println("Eduinq JSON Serialize Example");
9 Gson gson=new Gson();
10 Student s=new Student(1,"Arun");
11 String json=gson.toJson(s);
12 System.out.println("Eduinq JSON: "+json);
13 }
14 }

Program Output

					Eduinq JSON Serialize Example
Eduinq JSON: {"id":1,"name":"Arun"}
				

Explanation

Uses Gson toJson() to convert object. - Produces JSON string. - Exception handling ensures safe operations. - In enterprise systems, JSON serialization supports APIs. Conclusion: Shows serializing objects to JSON.

Quick Links to Explore