Make sure to subscribe to our newsletter and be the first to know the news.
Make sure to subscribe to our newsletter and be the first to know the news.
This post we will work on converting a Java Bean Class to a JSON Object.
Let us consider a Java Bean Class by name Mobile.java
public class Mobile
{
//Variables
private String model;
private String company;
private String os;
private float price;
private boolean bluetooth;
// Constructor
public Mobile()
{
}
// Setters and Getters
public String getModel()
{
return model;
}
public void setModel(String model)
{
this.model = model;
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
public String getOs()
{
return os;
}
public void setOs(String os)
{
this.os = os;
}
public float getPrice()
{
return price;
}
public void setPrice(float price)
{
this.price = price;
}
public boolean isBluetooth()
{
return bluetooth;
}
public void setBluetooth(boolean bluetooth)
{
this.bluetooth = bluetooth;
}
}
When you create a Java Bean class , you should follow basic Java Bean Rules and those are
Class should be of nature public
There should be a public no-args constructor
All the variables should be of nature private
All the setters and getters methods should be of nature public
For setter methods -- All the method name should be variable name prefixed with "set" and for boolean type it should be prefixed with "is", and return type should be void.
For getter methods -- All the method name should be variable name prefixed with "get" and it's return type should be the appropriate type.
We will create a JSONObject using a constructor which takes java.lang.Object as an argument.
JSONObject(java.lang.Object bean) -- Converts a Java Bean object to JSONObject using it's type
import org.json.*;
class ObjectToJSON
{
public static void main(String[] args)
{
Mobile m=new Mobile();
m.setCompany("Samsung");
m.setModel("Galaxy S10");
m.setBluetooth(true);
m.setOs("Android");
m.setPrice(50000.00f);
JSONObject obj=new JSONObject(m);
String jsonString=obj.toString(5);
System.out.println(jsonString);
}
}
Output:
{
"bluetooth": true,
"os": "Android",
"price": 50000,
"model": "Galaxy S10",
"company": "Samsung"
}
JAVA-Json Framework doesn't have options for converting a JSONObject back to Java Bean Object, for that you can make use of GSON or Jackson JSON API Framework.