Java

Converting a Java Bean Object to JSON using JSON-Java Framework

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

  1. Class should be of nature public

  2. There should be a public no-args constructor

  3. All the variables should be of nature private

  4. All the setters and getters methods should be of nature public

  5. 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.

  6. 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.

Related Posts

Table Of Contents

;