![]() |
VOOZH | about |
JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format. It is easy to read, write, and parse, making it widely used for data transfer between applications. JSON supports two main structured types:
Values can be strings, numbers, booleans, null, objects, or arrays.
Sample JSON Structure.
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
Java does not have built-in JSON parsing support before Java 9, so external libraries are commonly used. In this article, we use JSON.simple, a lightweight and easy-to-use library.
Maven Dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Class | Purpose |
|---|---|
JSONObject | Represents a JSON object (Map-like) |
JSONArray | Represents a JSON array (List-like) |
JSONParser | Parses JSON text into Java objects |
This example creates a JSON object and writes it to a file using JSONObject and JSONArray.
Output (JSONExample.json)
Note : JSON objects are unordered by definition, so key order is not guaranteed.
This example reads and parses the previously created JSON file.
Output: