উদাহরণ সহ API Response হ্যান্ডল করা

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

303

এটি একটি সাধারণ উদাহরণ যেখানে আমরা JSON.simple লাইব্রেরি ব্যবহার করে একটি API response হ্যান্ডল করব। API response সাধারণত JSON ফরম্যাটে আসে, এবং আমাদের সেই JSON ডেটা পার্স (deserialize) করে Java objects-এ রূপান্তর করতে হয়।

ধরা যাক, আমাদের একটি API response এসেছে যেটি একজন ব্যবহারকারীর তথ্য প্রদান করে। সেই JSON response থেকে আমরা নাম, বয়স, ঠিকানা, এবং ফোন নম্বর বের করতে চাই।


API Response Example

এটি একটি API response যা JSON ফরম্যাটে এসেছে:

{
  "status": "success",
  "data": {
    "id": 1,
    "name": "John Doe",
    "age": 30,
    "address": {
      "street": "123 Main St",
      "city": "New York",
      "zipcode": "10001"
    },
    "phones": [
      {"type": "home", "number": "123-4567"},
      {"type": "mobile", "number": "987-6543"}
    ]
  }
}

এখানে:

  • "status" হলো API এর স্টেটাস (যেমন success বা error),
  • "data" একটি nested object যা ব্যবহারকারীর তথ্য ধারণ করছে,
  • "address" একটি nested object এবং "phones" একটি array যা ফোন নম্বর ধারণ করছে।

API Response Handling in Java with JSON.simple

এখন আমরা JSON.simple ব্যবহার করে এই JSON API response পার্স (deserialize) করব এবং Java objects-এ রূপান্তর করব।

1. Java Classes তৈরি করা

প্রথমে আমাদের জন্য কিছু Java classes তৈরি করতে হবে যেখানে আমরা API response ডেটা রিসিভ করতে পারব।

User Class (Main Object)

import java.util.List;

public class User {
    private int id;
    private String name;
    private int age;
    private Address address;
    private List<Phone> phones;

    // Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public List<Phone> getPhones() {
        return phones;
    }

    public void setPhones(List<Phone> phones) {
        this.phones = phones;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", phones=" + phones + "]";
    }
}

Address Class (Nested Object)

public class Address {
    private String street;
    private String city;
    private String zipcode;

    // Getters and Setters
    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    @Override
    public String toString() {
        return "Address [street=" + street + ", city=" + city + ", zipcode=" + zipcode + "]";
    }
}

Phone Class (Array Elements)

public class Phone {
    private String type;
    private String number;

    // Getters and Setters
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return "Phone [type=" + type + ", number=" + number + "]";
    }
}

2. JSON Response Parsing with JSON.simple

এখন, JSON.simple ব্যবহার করে API response পার্স (deserialize) করব এবং Java objects-এ রূপান্তর করব।

JSON Response Parsing Example:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.util.ArrayList;
import java.util.List;

public class ApiResponseHandlingExample {
    public static void main(String[] args) {
        // JSON API Response
        String apiResponse = "{"
                + "\"status\": \"success\","
                + "\"data\": {"
                + "\"id\": 1,"
                + "\"name\": \"John Doe\","
                + "\"age\": 30,"
                + "\"address\": {"
                + "\"street\": \"123 Main St\","
                + "\"city\": \"New York\","
                + "\"zipcode\": \"10001\""
                + "},"
                + "\"phones\": ["
                + "{\"type\": \"home\", \"number\": \"123-4567\"},"
                + "{\"type\": \"mobile\", \"number\": \"987-6543\"}"
                + "]"
                + "}"
                + "}";

        JSONParser parser = new JSONParser();

        try {
            // Parse the JSON string into JSONObject
            JSONObject jsonObject = (JSONObject) parser.parse(apiResponse);

            // Extract the "data" object
            JSONObject data = (JSONObject) jsonObject.get("data");

            // Deserialize the User object
            int id = ((Long) data.get("id")).intValue();
            String name = (String) data.get("name");
            int age = ((Long) data.get("age")).intValue();

            // Deserialize the Address object (nested)
            JSONObject addressJson = (JSONObject) data.get("address");
            Address address = new Address();
            address.setStreet((String) addressJson.get("street"));
            address.setCity((String) addressJson.get("city"));
            address.setZipcode((String) addressJson.get("zipcode"));

            // Deserialize the phones array (JSON array)
            JSONArray phonesJson = (JSONArray) data.get("phones");
            List<Phone> phones = new ArrayList<>();
            for (Object phoneObj : phonesJson) {
                JSONObject phoneJson = (JSONObject) phoneObj;
                Phone phone = new Phone();
                phone.setType((String) phoneJson.get("type"));
                phone.setNumber((String) phoneJson.get("number"));
                phones.add(phone);
            }

            // Create the User object
            User user = new User();
            user.setId(id);
            user.setName(name);
            user.setAge(age);
            user.setAddress(address);
            user.setPhones(phones);

            // Print the User object
            System.out.println(user);

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

Explanation of the Code:

  1. JSONParser ব্যবহার করে API response (JSON string) প্যার্স করা হয়েছে।
  2. data অংশের মধ্যে থাকা Address এবং phones অ্যারের ডেটা প্যার্স করা হয়েছে।
  3. Address অবজেক্ট তৈরি করা হয়েছে এবং phones অ্যারে থেকে ফোন নম্বর পার্স করা হয়েছে।
  4. User অবজেক্টে সব ডেটা সেট করা হয়েছে।

Output:

User [id=1, name=John Doe, age=30, address=Address [street=123 Main St, city=New York, zipcode=10001], phones=[Phone [type=home, number=123-4567], Phone [type=mobile, number=987-6543]]]

এখানে, User অবজেক্টে সমস্ত nested JSON অবজেক্ট (যেমন address) এবং array (যেমন phones) সঠিকভাবে পার্স করা হয়েছে।


3. JSON Response Serialization

এখন আমরা Java objects কে আবার JSON string-এ রূপান্তর (serialization) করব।

Java Objects to JSON Serialization Example:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class ApiResponseSerialization {
    public static void main(String[] args) {
        // Create User object
        User user = new User();
        user.setId(1);
        user.setName("John Doe");
        user.setAge(30);

        // Set Address
        Address address = new Address();
        address.setStreet("123 Main St");
        address.setCity("New York");
        address.setZipcode("10001");
        user.setAddress(address);

        // Set Phones
        List<Phone> phones = new ArrayList<>();
        Phone phone1 = new Phone();
        phone1.setType("home");
        phone1.setNumber("123-4567");
        phones.add(phone1);
        Phone phone2 = new Phone();
        phone2.setType("mobile");
        phone2.setNumber("987-6543");
        phones.add(phone2);
        user.setPhones(phones);

        // Convert User object to JSON
        JSONObject userJson = new JSONObject();
        userJson.put("id", user.getId());
        userJson.put("name", user.getName());

        // Serialize Address
        JSONObject addressJson = new JSONObject();
        addressJson.put("street", user.getAddress().getStreet());
        addressJson.put("city", user.getAddress().getCity());
        addressJson.put("zipcode", user.getAddress().getZipcode());
        userJson.put("address", addressJson);

        // Serialize Phones
        JSONArray phonesJson = new JSONArray();
        for (Phone phone : user.getPhones()) {
            JSONObject phoneJson = new JSONObject();
            phoneJson.put("type", phone.getType());
            phoneJson.put("number", phone.getNumber());
            phonesJson.add(phoneJson);
        }
        userJson.put("phones", phonesJson);

        //

Print the JSON string System.out.println(userJson.toJSONString()); } }


#### **Output:**
```json
{
  "id": 1,
  "name": "John Doe",
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zipcode": "10001"
  },
  "phones": [
    {
      "type": "home",
      "number": "123-4567"
    },
    {
      "type": "mobile",
      "number": "987-6543"
    }
  ]
}

এখানে, আমরা Java objects (যেমন User, Address, এবং Phone) কে JSON এ রূপান্তর করেছি।


  1. JSON.simple লাইব্রেরি ব্যবহার করে API response থেকে nested JSON অবজেক্ট এবং arrays সহজে পার্স করা যায়।
  2. Java POJO ক্লাস ব্যবহার করে ডেটা মডেলিং করা এবং JSON থেকে ডেটা এক্সট্র্যাক্ট করা খুব সহজ।
  3. Serialization এবং Deserialization এর মাধ্যমে JSON ডেটার সাথে Java objects এর কাজ করা কার্যকরী।

এই প্রক্রিয়া REST API ইন্টিগ্রেশনের সময় JSON ডেটার সঙ্গে কার্যকরীভাবে কাজ করতে সাহায্য করবে।

Content added By
Promotion

Are you sure to start over?

Loading...