REST API এর JSON Response Parsing করা

JSON.simple এর মাধ্যমে REST API Response হ্যান্ডলিং - জেসন.সিম্পল (Json.Simple) - Java Technologies

358

REST API থেকে JSON রেসপন্স পেয়ে সেই ডেটা Json.Simple লাইব্রেরি ব্যবহার করে পার্স করা একটি সাধারণ এবং কার্যকরী প্রক্রিয়া। সাধারণত, REST API গুলি JSON ফরম্যাটে ডেটা ফেরত দেয়, এবং Json.Simple লাইব্রেরি সেই JSON রেসপন্সকে Java অবজেক্টে রূপান্তর করতে সাহায্য করে।

এখানে আমরা দেখব কিভাবে একটি REST API থেকে JSON রেসপন্স নিয়ে Json.Simple লাইব্রেরি দিয়ে তা পার্স করা যায়।


1. Required Libraries

REST API থেকে JSON রেসপন্স পেতে আমরা HttpURLConnection অথবা Apache HttpClient লাইব্রেরি ব্যবহার করতে পারি। রেসপন্স পরবর্তীতে Json.Simple দিয়ে পার্স করা হবে।

Maven Dependencies:

<dependency>
    <groupId>org.json.simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

2. JSON Response Parsing from REST API using HttpURLConnection

এই উদাহরণে আমরা HttpURLConnection ব্যবহার করে একটি REST API কল করব এবং Json.Simple লাইব্রেরি ব্যবহার করে JSON রেসপন্স পার্স করব।

Example: REST API JSON Response Parsing using HttpURLConnection

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JsonApiParserExample {
    public static void main(String[] args) {
        try {
            // REST API URL (JSON response)
            String url = "https://jsonplaceholder.typicode.com/todos/1";

            // Create URL object
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // Setting the request method
            con.setRequestMethod("GET");

            // Read the response
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // Parse the JSON response
            String jsonResponse = response.toString();
            JSONParser parser = new JSONParser();
            JSONObject jsonObject = (JSONObject) parser.parse(jsonResponse);

            // Extract data from JSON
            long userId = (long) jsonObject.get("userId");
            long id = (long) jsonObject.get("id");
            String title = (String) jsonObject.get("title");
            boolean completed = (boolean) jsonObject.get("completed");

            // Print the parsed JSON data
            System.out.println("User ID: " + userId);
            System.out.println("ID: " + id);
            System.out.println("Title: " + title);
            System.out.println("Completed: " + completed);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  1. HttpURLConnection: ব্যবহার করে আমরা REST API থেকে GET রিকোয়েস্ট পাঠাচ্ছি এবং JSON রেসপন্স গ্রহণ করছি।
  2. BufferedReader: API থেকে JSON রেসপন্স পড়তে ব্যবহৃত হচ্ছে।
  3. JSONParser: Json.Simple লাইব্রেরি ব্যবহার করে JSON স্ট্রিং পার্স করা হচ্ছে।
  4. JSONObject: পার্স করা JSON রেসপন্স থেকে বিভিন্ন ফিল্ড এক্সট্র্যাক্ট করা হচ্ছে (যেমন userId, id, title, completed)।

Output:

User ID: 1
ID: 1
Title: delectus aut autem
Completed: false

এখানে, আমরা https://jsonplaceholder.typicode.com/todos/1 URL থেকে JSON রেসপন্স পেয়ে তা পার্স করেছি। JSON রেসপন্সে userId, id, title, এবং completed ফিল্ড রয়েছে, যা পার্স করে প্রিন্ট করা হয়েছে।


3. JSON Response Parsing using Apache HttpClient

যদি আপনি Apache HttpClient ব্যবহার করতে চান, তাহলে আপনি এই লাইব্রেরি দিয়ে HTTP রিকোয়েস্ট করতে পারেন। এটি আরও উন্নত এবং সুবিধাজনক অপশন যখন আপনার বিভিন্ন ধরনের HTTP রিকোয়েস্ট করতে হয়, যেমন POST, PUT, DELETE ইত্যাদি।

Example: REST API JSON Response Parsing using Apache HttpClient

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class JsonApiWithHttpClient {
    public static void main(String[] args) {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // REST API URL
            String url = "https://jsonplaceholder.typicode.com/todos/1";

            // HTTP GET request
            HttpGet request = new HttpGet(url);

            // Execute the request
            HttpResponse response = client.execute(request);

            // Read the response
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder responseContent = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseContent.append(inputLine);
            }

            // Parse the JSON response
            String jsonResponse = responseContent.toString();
            JSONParser parser = new JSONParser();
            JSONObject jsonObject = (JSONObject) parser.parse(jsonResponse);

            // Extract and print data from JSON
            long userId = (long) jsonObject.get("userId");
            long id = (long) jsonObject.get("id");
            String title = (String) jsonObject.get("title");
            boolean completed = (boolean) jsonObject.get("completed");

            System.out.println("User ID: " + userId);
            System.out.println("ID: " + id);
            System.out.println("Title: " + title);
            System.out.println("Completed: " + completed);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  1. Apache HttpClient: HTTP GET রিকোয়েস্ট তৈরি করা হয়েছে এবং সেটি execute করা হয়েছে।
  2. BufferedReader: API থেকে রেসপন্স পড়ে সেটিকে JSON স্ট্রিংতে রূপান্তর করা হয়েছে।
  3. JSONParser: JSON রেসপন্স পার্স করা হয়েছে এবং JSONObject তে রূপান্তরিত করা হয়েছে।

Output:

User ID: 1
ID: 1
Title: delectus aut autem
Completed: false

এখানে আমরা Apache HttpClient ব্যবহার করে JSON রেসপন্স পেয়েছি এবং Json.Simple দিয়ে পার্স করেছি।


4. Error Handling in REST API Parsing

Example: Error Handling with Invalid JSON Response

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonErrorHandling {
    public static void main(String[] args) {
        String invalidJson = "{ \"name\": \"John\", \"age\": 30, }";  // Invalid JSON (trailing comma)

        try {
            JSONParser parser = new JSONParser();
            JSONObject jsonObject = (JSONObject) parser.parse(invalidJson);
            System.out.println(jsonObject.toJSONString());
        } catch (ParseException e) {
            System.out.println("Error: Invalid JSON format.");
            e.printStackTrace();
        }
    }
}

Output:

Error: Invalid JSON format.
org.json.simple.parser.ParseException: Unexpected character '}' at position 30.

Error Handling:

  • ParseException: যদি JSON অবজেক্ট বা অ্যারে ঠিকভাবে প্যার্স না করা যায় (যেমন, অতিরিক্ত কমা বা ভুল স্ট্রাকচার), ParseException ঘটবে।
  • Exception Handling: try-catch ব্লক ব্যবহার করে আমরা এই ধরনের ত্রুটি ধরতে পারি এবং উপযুক্ত বার্তা প্রদর্শন করতে পারি।

  1. Json.Simple লাইব্রেরি ব্যবহার করে REST API থেকে প্রাপ্ত JSON রেসপন্স খুব সহজে পার্স করা যায়।
  2. HttpURLConnection এবং Apache HttpClient এর মাধ্যমে REST API থেকে JSON রেসপন্স প্রাপ্তি সম্ভব।
  3. JSONParser ব্যবহার করে JSON স্ট্রিংকে JSONObject বা JSONArray তে রূপান্তর করা হয়।
  4. Error Handling গুরুত্বপূর্ণ, কারণ বিভিন্ন ধরনের সমস্যা হতে পারে যেমন invalid JSON ফরম্যাট, পার্সিং ত্রুটি ইত্যাদি।

এই প্রক্রিয়া আপনার Java অ্যাপ্লিকেশনে RESTful API ইন্টিগ্রেশন এবং JSON ডেটা ম্যানিপুলেশনকে সহজ এবং নিরাপদ করে তোলে।

Content added By
Promotion

Are you sure to start over?

Loading...