Categories
java

convert java object to JSON string

In this post, we will learn to convert java object to JSON string using GSON library

We can convert Java object to json string using below dependency

Dependency
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
Syntax
String jsonString = gson.toJson(student);
Example

import com.beginnersbug.example.model.Student;
import com.google.gson.Gson;

public class ConvertJavaToJson {

	public static void main(String[] args) {
		Gson gson = new Gson();
		Student student = new Student();
		student.setStudentId("001");
		student.setStudentName("Rajesh");
		student.setDepartment("JAVA");
		student.setSchoolName("BeginnersBug");

		String jsonString = gson.toJson(student);

		System.out.println(jsonString);

	}
}
Student.java
public class Student {

	private String studentId;

	private String studentName;

	private String schoolName;

	private String department;

	public String getStudentId() {
		return studentId;
	}

	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public String getSchoolName() {
		return schoolName;
	}

	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

}
Output
{"studentId":"001","studentName":"Rajesh","schoolName":"BeginnersBug","department":"JAVA"}
Github

https://github.com/rkumar9090/student-example/blob/master/src/main/java/com/beginnersbug/example/ConvertJavaToJson.java

Related Articles

convert JSON string to java object

Leave a Reply

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