How is the JSONObject used in Java?

JSONObject in Java is a class used for handling JSON data. It offers a set of methods to create, manipulate, and access JSON objects.

Some common ways to create a JSONObject object include using a constructor or parsing a JSON string. Below are examples of some commonly used methods:

  1. Create an empty JSONObject object:
JSONObject obj = new JSONObject();
  1. Create a JSONObject object from a JSON string.
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject obj = new JSONObject(jsonString);
  1. Add properties and values to a JSONObject object.
obj.put("name", "John");
obj.put("age", 30);
obj.put("city", "New York");
  1. Obtain the value of a property from a JSONObject.
String name = obj.getString("name");
int age = obj.getInt("age");
String city = obj.getString("city");
  1. Check if a JSONObject object contains a specific attribute.
boolean hasName = obj.has("name");
  1. Convert a JSONObject object to a JSON string.
String jsonString = obj.toString();

These are just examples of some common methods provided by the JSONObject class, in fact it offers many other methods for manipulating and accessing JSON data. You can refer to the corresponding documentation or API reference to learn more about its usage according to your needs.

bannerAds