How do I read values from JSONObject?

A JSONObject is an unordered collection of key-value pairs. To read values from the JSONObject we can use the get(String key) and opt(String key) methods. These generic methods return an Object, which you can cast to a certain type.

There are also typed get and opt methods to read value in specific type such as getString(), getInt(), getDouble(), optString(), optFloat(), optBigInteger(), optBoolean(), optEnum(), etc. For more detail, you can check the JSONObject API documentation.

The get methods throws JSONException when the key is not found in the JSONObject, while the opt methods does not throw exception but return null, and we can also pass a default value argument that will be returned when the key is not found.

The code below give you a simple example to read values from JSONObject.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ReadJSONValue {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        jsonObject.put("courses",
                new JSONArray(new String[] {"Engineering", "Finance"}));
        System.out.println(jsonObject);

        // Using get() and opt() methods we need to cast
        // the returned value to the type its store.
        long id1 = (long) jsonObject.get("id");
        String name1 = (String) jsonObject.get("name");
        int age1 = (int) jsonObject.get("age");
        JSONArray courses1 = (JSONArray) jsonObject.get("courses");

        // This will throw exception because JSONObject
        // does not have the address key in it.
        String address1;
        try {
            address1 = (String) jsonObject.get("address");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Using opt() method to read address, does not throw
        // exception
        address1 = (String) jsonObject.opt("address");

        System.out.println("id1      = " + id1);
        System.out.println("name1    = " + name1);
        System.out.println("age1     = " + age1);
        System.out.println("address1 = " + address1);
        System.out.println("courses1 = " + courses1);
        System.out.println();

        // Using data type specific get() and opt() methods.
        // We don't have to cast the return from the getXXX()
        // and optXXX() methods.
        long id2 = jsonObject.getLong("id");
        String name2 = jsonObject.getString("name");
        int age2 = jsonObject.optInt("age");

        // Using optString() to read address and provide default
        // value when address is not found.
        String address2 = jsonObject.optString("address", "No Address");
        JSONArray courses2 = jsonObject.optJSONArray("courses");

        System.out.println("id2      = " + id2);
        System.out.println("name2    = " + name2);
        System.out.println("age2     = " + age2);
        System.out.println("address2 = " + address2);
        System.out.println("courses2 = " + courses2);
    }
}

Running this code produces the following results:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
org.json.JSONException: JSONObject["address"] not found.
    at org.json.JSONObject.get(JSONObject.java:580)
    at org.kodejava.json.ReadJSONValue.main(ReadJSONValue.java:28)

id1      = 1
name1    = Alice
age1     = 20
address1 = null
courses1 = ["Engineering","Finance"]

id2      = 1
name2    = Alice
age2     = 20
address2 = No Address
courses2 = ["Engineering","Finance"]

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

How do I retrieve object from database in Hibernate?

In the How do I store object in Hibernate? example you’ll see how tho store objects into database. In this example we’ll extend the LabelService class and add the capability to get or query object from database.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

public class LabelService {
    public Label getLabel(Long id) {
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        // We get back Label object from database by calling the Session
        // object get() method and passing the object type and the object
        // id to be read.
        Label label = session.get(Label.class, id);
        session.getTransaction().commit();

        return label;
    }
}
package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

public class LoadDemo {
    public static void main(String[] args) {
        // Create an instance of LabelService.
        LabelService service = new LabelService();

        // We call the getLabel() method and pass the label id to load it
        // from the database and print out the label string.
        Label label = service.getLabel(1L);
        System.out.println("label = " + label);
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central