Monday, 29 March 2021

Javax.json: Convert object to json string

Step 1: Construct JsonObjectBuilder from an object properties.

JsonObjectBuilder objectBuilder = Json.createObjectBuilder()
.add("firstName", emp.getFirstName())
.add("lastName", emp.getLastName())
.add("id", emp.getId())
.add("birthdate", new SimpleDateFormat("DD/MM/YYYY").format(emp.getDateOfBirth()));

 

Step 2: Get JsonObject instance from JsonObjectBuilder.

JsonObject jsonObject = objectBuilder.build();

 

Step 3: Call toString() method on JsonObject.

 

Find the below working application.

 

Employee.java

 

package com.sample.app.model;

import java.util.Date;

public class Employee {

	private int id;
	private String firstName;
	private String lastName;
	private Date dateOfBirth;

	public Employee(int id, String firstName, String lastName, Date dateOfBirth) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.dateOfBirth = dateOfBirth;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

}

 

ObjectToJsonDemo.java

package com.sample.app;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;

import com.sample.app.model.Employee;

public class ObjectToJsonDemo {
	private static String getJson(Employee emp) {
		if (emp == null) {
			return "";
		}

		JsonObjectBuilder objectBuilder = Json.createObjectBuilder()
				.add("firstName", emp.getFirstName())
				.add("lastName", emp.getLastName())
				.add("id", emp.getId())
				.add("birthdate", new SimpleDateFormat("DD/MM/YYYY").format(emp.getDateOfBirth()));

		JsonObject jsonObject = objectBuilder.build();

		return jsonObject.toString();
	}

	public static void main(String args[]) {
		LocalDate dateOfBirth = LocalDate.of(1985, 1, 10);
		Date date = Date.from(dateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());

		Employee emp1 = new Employee(32, "Ram", "Gurram", date);

		System.out.println(getJson(emp1));
	}

}

Output

{"firstName":"Ram","lastName":"Gurram","id":32,"birthdate":"10/01/1985"}




 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment