JSON.simple লাইব্রেরি ব্যবহার করে API response এর মধ্যে nested JSON পার্স করা সহজ। API response সাধারণত JSON ফরম্যাটে আসে, এবং এতে বিভিন্ন nested JSON objects এবং JSON arrays থাকতে পারে। এই ডেটা পার্স করে আমরা যেকোনো মান বা অবজেক্ট Java objects বা JSONObject-এ রূপান্তর করতে পারি।
ধরা যাক, একটি API response আমাদের নিম্নলিখিত JSON ডেটা পাঠাচ্ছে:
{
"status": "success",
"data": {
"user": {
"id": 101,
"name": "John Doe",
"email": "johndoe@example.com"
},
"posts": [
{
"id": 1,
"title": "My First Post",
"content": "This is the content of the first post"
},
{
"id": 2,
"title": "Another Post",
"content": "This is the content of another post"
}
]
}
}
এখানে, "data" একটি নেস্টেড অবজেক্ট যা "user" এবং "posts" নামে দুটি কীগুলির মধ্যে বিভিন্ন ডেটা ধারণ করছে। আমাদের "user" অবজেক্ট এবং "posts" অ্যারে থেকে ডেটা বের করতে হবে।
Step-by-Step: Nested JSON Parsing with JSON.simple
Step 1: JSON Response Parsing
আমরা প্রথমে JSON response থেকে nested JSON পার্স করব এবং তারপর user এবং posts এর তথ্য বের করব।
Example Code: Nested JSON Parsing
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class NestedJsonParsingExample {
public static void main(String[] args) {
// API response JSON string (simulate a response from an API)
String apiResponse = "{"
+ "\"status\": \"success\","
+ "\"data\": {"
+ "\"user\": {\"id\": 101, \"name\": \"John Doe\", \"email\": \"johndoe@example.com\"},"
+ "\"posts\": ["
+ "{\"id\": 1, \"title\": \"My First Post\", \"content\": \"This is the content of the first post\"},"
+ "{\"id\": 2, \"title\": \"Another Post\", \"content\": \"This is the content of another post\"}"
+ "]"
+ "}"
+ "}";
// JSONParser to parse the JSON string
JSONParser parser = new JSONParser();
try {
// Parse the response into a JSONObject
JSONObject jsonObject = (JSONObject) parser.parse(apiResponse);
// Get the "data" object from the response
JSONObject data = (JSONObject) jsonObject.get("data");
// Parse user details (nested JSON object)
JSONObject user = (JSONObject) data.get("user");
Long userId = (Long) user.get("id");
String userName = (String) user.get("name");
String userEmail = (String) user.get("email");
// Parse posts (nested JSON array)
JSONArray posts = (JSONArray) data.get("posts");
// Print user details
System.out.println("User ID: " + userId);
System.out.println("User Name: " + userName);
System.out.println("User Email: " + userEmail);
// Iterate over the posts array and print post details
System.out.println("\nPosts:");
for (Object postObj : posts) {
JSONObject post = (JSONObject) postObj;
Long postId = (Long) post.get("id");
String postTitle = (String) post.get("title");
String postContent = (String) post.get("content");
System.out.println("Post ID: " + postId);
System.out.println("Post Title: " + postTitle);
System.out.println("Post Content: " + postContent);
System.out.println();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
ব্যাখ্যা:
- API Response: একটি সিমুলেটেড JSON স্ট্রিং তৈরি করা হয়েছে, যা API response হিসেবে ধরানো হচ্ছে।
- JSONParser: JSONParser ব্যবহার করে JSON স্ট্রিংটিকে JSONObject-এ রূপান্তর করা হয়েছে।
- Nested JSON Object:
dataঅবজেক্টের মধ্যে থাকা user অবজেক্ট এবং posts অ্যারে থেকে ডেটা বের করা হয়েছে। - Looping Through JSON Array: posts অ্যারে-তে থাকা প্রতিটি পোস্ট অবজেক্ট থেকে তথ্য বের করতে for loop ব্যবহার করা হয়েছে।
Output:
User ID: 101
User Name: John Doe
User Email: johndoe@example.com
Posts:
Post ID: 1
Post Title: My First Post
Post Content: This is the content of the first post
Post ID: 2
Post Title: Another Post
Post Content: This is the content of another post
Step 2: Handling Errors in JSON Parsing
JSON.simple লাইব্রেরি ব্যবহার করে JSON পার্স করার সময়ে কিছু ভুল ফরম্যাট বা ভুল ডেটার কারণে ParseException ঘটতে পারে। সঠিকভাবে এ ধরনের ত্রুটি হ্যান্ডেল করা অত্যন্ত গুরুত্বপূর্ণ।
Error Handling Example:
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParsingErrorHandling {
public static void main(String[] args) {
// Invalid JSON string (missing comma between values)
String invalidJsonString = "{\"status\":\"success\",\"data\":{\"user\":{\"id\":101,\"name\":\"John\" \"email\":\"john@example.com\"}}}";
// JSONParser to parse the JSON string
JSONParser parser = new JSONParser();
try {
// Attempt to parse the invalid JSON string
parser.parse(invalidJsonString);
} catch (ParseException e) {
// Handle invalid JSON format error
System.out.println("Error: Invalid JSON format");
e.printStackTrace();
}
}
}
Output:
Error: Invalid JSON format
org.json.simple.parser.ParseException: Expected ':' after field name at position 40
Step 3: Parsing Nested JSON with Different Data Types
আপনার API response-এ যদি বিভিন্ন ধরনের ডেটা থাকে (যেমন String, Long, Boolean, JSONArray), তবে সেগুলো সঠিকভাবে পার্স করতে হবে। এটি বিশেষভাবে গুরুত্বপূর্ণ যখন আপনি JSONArray তে থাকা nested JSON objects থেকে ডেটা বের করতে চান।
Example with Mixed Data Types:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class MixedDataTypesParsing {
public static void main(String[] args) {
// Nested JSON response (mixed data types)
String jsonString = "{"
+ "\"status\": \"success\","
+ "\"data\": {"
+ "\"user\": {\"id\": 101, \"name\": \"John Doe\", \"isActive\": true},"
+ "\"posts\": ["
+ "{\"id\": 1, \"title\": \"First Post\", \"isPublished\": true},"
+ "{\"id\": 2, \"title\": \"Second Post\", \"isPublished\": false}"
+ "]"
+ "}"
+ "}";
// Parse and extract mixed data types
JSONParser parser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
// Extract user data
JSONObject data = (JSONObject) jsonObject.get("data");
JSONObject user = (JSONObject) data.get("user");
Long userId = (Long) user.get("id");
String userName = (String) user.get("name");
Boolean isActive = (Boolean) user.get("isActive");
// Extract posts
JSONArray posts = (JSONArray) data.get("posts");
for (Object postObj : posts) {
JSONObject post = (JSONObject) postObj;
Long postId = (Long) post.get("id");
String postTitle = (String) post.get("title");
Boolean isPublished = (Boolean) post.get("isPublished");
System.out.println("Post ID: " + postId);
System.out.println("Post Title: " + postTitle);
System.out.println("Is Published: " + isPublished);
System.out.println();
}
System.out.println("User ID: " + userId);
System.out.println("User Name: " + userName);
System.out.println("Is Active: " + isActive);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Post ID: 1
Post Title: First Post
Is Published: true
Post ID: 2
Post Title: Second Post
Is Published: false
User ID: 101
User Name: John Doe
Is Active: true
- Nested JSON Parsing: JSON.simple লাইব্রেরি ব্যবহার করে nested JSON objects এবং JSON arrays এর মধ্যে থাকা ডেটা সহজে পার্স করা যায়।
- Error Handling: JSON পার্সিংয়ের সময় ভুল ফরম্যাট বা ত্রুটিপূর্ণ ডেটার কারণে ParseException হতে পারে, তাই এই ত্রুটিগুলি হ্যান্ডল করা গুরুত্বপূর্ণ।
- Mixed Data Types: JSON ডেটা বিভিন্ন ধরনের ডেটা ধারণ করতে পারে (যেমন, String, Long, Boolean, JSONArray), এবং প্রতিটি ডেটা টাইপের জন্য সঠিক কাস্টমাইজেশন প্রয়োজন।
JSON.simple লাইব্রেরি ব্যবহার করে API response থেকে JSON ডেটা পার্স এবং ম্যানিপুলেশন খুবই কার্যকরী এবং সহজ, এবং এটি Java-এ JSON ডেটার সাথে কাজ করার জন্য একটি শক্তিশালী টুল।
Read more