json
  1. java-json-example

Java JSON Example

Java provides support for working with JSON data using the JSONObject class from the org.json package.

Syntax

// Parsing JSON String to Object
JSONObject jsonObject = new JSONObject(jsonString);

// Creating JSON Object
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");

// Converting Object to JSON String
jsonObject.toString();

Example

import org.json.*;

public class JsonExample {
   public static void main(String[] args) {
      String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
      JSONObject jsonObject = new JSONObject(jsonString);
      System.out.println("Name: " + jsonObject.getString("name"));
      System.out.println("Age: " + jsonObject.getInt("age"));
      System.out.println("City: " + jsonObject.getString("city"));
      
      JSONObject newJsonObject = new JSONObject();
      newJsonObject.put("key1", "value1");
      newJsonObject.put("key2", "value2");
      String jsonStr = newJsonObject.toString();
      System.out.println("JSON String: " + jsonStr);
   }
}

Output

Name: John
Age: 30
City: New York
JSON String: {"key1":"value1","key2":"value2"}

Explanation

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write. It is also easy for machines to parse and generate. JSON data can be represented as a string, object, or array. In Java, JSON data can be parsed using the JSONObject class from the org.json package.

The example code demonstrates how to parse JSON data, create a JSON object, and convert a Java object to JSON data. The JSONObject constructor is used to parse a JSON string into a Java object. The put() method is used to add key-value pairs to a JSON object. The toString() method is used to convert a JSON object to a string.

Use

The JSONObject class can be used to parse and generate JSON data in Java. It can be used to exchange data between different systems and languages. JSON data can be exchanged over the network and stored in files. It can also be used to represent configuration data for Java applications.

Important Points

  • The JSONObject class is used to parse and generate JSON data in Java.
  • JSON data can be represented as a string, object, or array.
  • JSON data can be exchanged over the network and stored in files.
  • JSON data can be used to represent configuration data for Java applications.

Summary

Java provides support for working with JSON data using the JSONObject class from the org.json package. JSON data can be parsed, generated, and exchanged using the JSONObject class. JSON data can be represented as a string, object, or array. JSON data can be used to represent configuration data for Java applications.

Published on: