Convert Java Object to / from JSON | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link



Download Code and Jars : Link

File : EmployeeBean.java

package com.codeFactory.bean;

public class EmployeeBean {

	private int id;
	private String name;
	private String gender;
	private String designation;

	// Getters and Setters...
	
}

File : Main.java

package com.codeFactory.main;

import com.codeFactory.bean.EmployeeBean;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
	public static void main(String args[]) {
		EmployeeBean employeeBean = new EmployeeBean();
		employeeBean.setId(1);
		employeeBean.setName("Employee1");
		employeeBean.setGender("Male");
		employeeBean.setDesignation("JAVA");
		ObjectMapper objectMapper = new ObjectMapper();

		try
		{
			// this create java object to json string...
			String jsonStr = objectMapper.writeValueAsString(employeeBean);
			System.out.println(jsonStr);

			// this create json string to java object...
			EmployeeBean employeeBean2 = new EmployeeBean();
			jsonStr = "{\"id\":\"2\",\"name\":\"Code Factory\"}";
			employeeBean2 = objectMapper.readValue(jsonStr, EmployeeBean.class);
			System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeBean2));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s