JSON (JavaScript Object Notation)
1.What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It has become the de-facto standard for client-server communication in RESTful APIs, microservices, and even configuration files.
Why JSON is so popular:
- ✅ Easy to read and write – its structure is straightforward and resembles objects in many programming languages.
- ✅ Language-independent – JSON is not tied to JavaScript; almost every modern language (Java, Python, PHP, C#, etc.) supports JSON parsing.
✅ Flexible data representation – JSON can represent different kinds of values, such as:
Objects (key/value pairs)- Arrays (ordered lists)
- Numbers
- Strings
- Booleans (
true/false) - Null values
- Because of this simplicity, JSON has almost completely replaced XML in most APIs.
2.JSON Syntax Rules
- Data is in key/value pairs →
"key": "value". - Keys are always strings (inside double quotes).
Values can be:
- String →
"Hello" - Number →
25 - Boolean →
true/false - Null →
null - Array →
[1,2,3] - Object →
{ "key": "value" }
{"name":"Ashish","age":25,"isStudent":false,"skills": ["Java", "Spring Boot", "SQL"],"address": {"city":"Delhi","pincode":110001} }
3.JSONObject
A JSONObject in Java represents a collection of key-value pairs, very similar to a Map<String, Object>.
✅ Key points about JSONObject:
- Keys must be unique and non-null strings.
Values can be:
- String →
"Hello" - Number →
100 - Boolean →
true / false - JSONArray →
[ ... ] - Another JSONObject →
{ ... } - or
JSONObject.NULL(if you want a null value). - The data is wrapped in curly braces
{ }, with keys and values separated by:and each pair separated by a comma.
3.1 Creating a JSONObject Manually
We can create a new JSONObject and add properties using the put() method:
importorg.json.JSONObject;public classJsonExample{public static voidmain(String[] args) {JSONObject user=newJSONObject(); user.put("id",101); user.put("name","Alice"); user.put("isPremium",true); System.out.println(user.toString()); } }
Output:
{"id":101,"name":"Alice","isPremium":true}
3.2 Creating JSONObject from JSON String
If you already have a JSON string, just pass it into the constructor:
String jsonString = "{\"course\":\"Java\",\"level\":\"Beginner\"}"; JSONObject course = new JSONObject(jsonString); System.out.println(course.getString("course")); // Java System.out.println(course.getString("level")); // Beginner
3.3 Nested JSONObject
You can also store JSON objects inside another JSON object:
JSONObject address = new JSONObject();
address.put("city", "Mumbai");
address.put("pincode", 400001);
JSONObject student = new JSONObject();
student.put("name", "Ravi");
student.put("rollNo", 12);
student.put("address", address);
System.out.println(student.toString(2)); Output :
{
"name": "Ravi",
"rollNo": 12,
"address": {
"city": "Mumbai",
"pincode": 400001
}
}4.JSON Array
A JSONArray is an ordered list of values, very similar to a Java List.
Key points about JSONArray:
- Values can be Strings, Numbers, Booleans, JSONObjects, or even other JSONArrays.
- It is enclosed in square brackets
[ ]. - Each value is separated by a comma.
4.1 Creating JSONArray Manually
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonArrayExample {
public static void main(String[] args) {
JSONArray fruits = new JSONArray();
fruits.put("Apple");
fruits.put("Banana");
fruits.put("Mango");
System.out.println(fruits.toString());
}
}Output:
["Apple","Banana","Mango"]4.2 JSONArray with JSONObjects
You can add JSON objects into an array as well:
JSONObject book1 = new JSONObject();
book1.put("title", "Clean Code");
book1.put("author", "Robert Martin");
JSONObject book2 = new JSONObject();
book2.put("title", "Effective Java");+
book2.put("author", "Joshua Bloch");
JSONArray library = new JSONArray();
library.put(book1);
library.put(book2);
System.out.println(library.toString(2));Output :
[
{
"title": "Clean Code",
"author": "Robert Martin"
},
{
"title": "Effective Java",
"author": "Joshua Bloch"
}
]4.3 Creating JSONArray from Collection
List<String> cities = Arrays.asList("Delhi", "London", "New York");
JSONArray cityArray = new JSONArray(cities);
System.out.println(cityArray.toString());Output:
["Delhi","London","New York"]5.HTTP
The HTTP class in the org.json package helps us work with HTTP headers. It provides simple methods to convert between:
-
an HTTP header string →
JSONObject - a JSONObject → HTTP header string
Main Methods of HTTP Class:
toJSONObject(String sourceHttpHeader)- Takes a plain HTTP header string.
- Converts it into a structured
JSONObject.
toString(JSONObject jo)
- Takes a
JSONObject. - Converts it into an HTTP header string.
5.1 Converting JSONObject to an HTTP Header
The HTTP class in the org.json package lets us convert a JSONObject into an HTTP header string.To make a valid HTTP request header, our JSONObject must contain three required keys:
"Method" – the HTTP method (GET, POST, PUT, DELETE, etc.)"Request-URI" – the resource URL we want to call"HTTP-Version" – the HTTP version (usually HTTP/1.1)
Example:import org.json.JSONObject;
import org.json.HTTP;
public class HttpHeaderExample {
public static void main(String[] args) {
JSONObject requestHeader = new JSONObject();
requestHeader.put("Method", "GET");
requestHeader.put("Request-URI", "https://api.myapp.com/users");
requestHeader.put("HTTP-Version", "HTTP/1.1");
String httpStr = HTTP.toString(requestHeader);
System.out.println(httpStr);
}
}
Output:
GET "https://api.myapp.com/users" HTTP/1.1📌 Important Notes:
- For request headers, you must include:
- "Method"
- "Request-URI"
- "HTTP-Version"
For response headers, you must include:
"HTTP-Version""Status-Code"(e.g., 200, 404)"Reason-Phrase"(e.g., OK, Not Found)
HTTP.toString() method makes it easy to transform a JSON object into a proper HTTP header string.Just like we can convert a JSONObject into an HTTP header string, we can also do the reverse — take an HTTP header string and turn it back into a JSONObject.
For this, we use the method:
HTTP.toJSONObject(String httpHeaderString)
import org.json.JSONObject;
import org.json.HTTP;
public class HttpHeaderBackExample {
public static void main(String[] args) {
String httpHeader = "GET \"https://api.shop.com/products\" HTTP/1.1";
JSONObject obj = HTTP.toJSONObject(httpHeader);
System.out.println(obj.toString(2)); // pretty print
}
}Output :
{
"Method": "GET",
"Request-URI": "https://api.shop.com/products",
"HTTP-Version": "HTTP/1.1"
}📌 Key Point:
-
HTTP.toJSONObject()is useful when you receive raw HTTP headers as text and want to parse them into a structuredJSONObjectfor further processing.
skks
No comments:
Post a Comment