Polymorphic Serialization এবং Deserialization

Gson এর Runtime Type Adapter - জিসন (Gson) - Java Technologies

331

Polymorphic Serialization এবং Deserialization হলো এমন একটি প্রক্রিয়া যেখানে একাধিক সাবক্লাস (Subclasses) একই সুপারক্লাস (Superclass) থেকে ইনহেরিট (inherit) করে এবং Gson তার উপর নির্ভর করে সিরিয়ালাইজেশন ও ডেসিরিয়ালাইজেশন পরিচালনা করে। এর মাধ্যমে আমরা একটি বেস ক্লাসের জন্য বিভিন্ন সাবক্লাসের নির্দিষ্ট ডেটা সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করতে পারি।

Gson লাইব্রেরি সাধারণত polymorphic অবজেক্টের জন্য সঠিক সাবক্লাসটি নির্ধারণ করতে পারে না, কারণ JSON ডেটায় কোনও ধরণের টাইপ ইনফরমেশন থাকে না। তবে, এটি @SerializedName অ্যানোটেশন এবং কাস্টম সিরিয়ালাইজার এবং ডেসিরিয়ালাইজার ব্যবহার করে সমাধান করা যায়।

উদাহরণ: Polymorphic Serialization এবং Deserialization

ধরা যাক, আমাদের একটি Shape নামক বেস ক্লাস এবং এর দুটি সাবক্লাস Circle এবং Rectangle রয়েছে। আমরা চাই যে, JSON ডেটাতে টাইপ ইনফরমেশন ব্যবহার করে সাবক্লাস ডেটা সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করা হোক।

1. ডিপেনডেন্সি যোগ করুন:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>

2. Polymorphic Serialization ও Deserialization এর জন্য ক্লাস:

import com.google.gson.*;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Type;

abstract class Shape {
    @SerializedName("type")
    private String type;

    // Getter method
    public String getType() {
        return type;
    }
}

class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }
}

class Rectangle extends Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getWidth() {
        return width;
    }

    public double getHeight() {
        return height;
    }
}

// Polymorphic Serializer
class ShapeSerializer implements JsonSerializer<Shape> {
    @Override
    public JsonElement serialize(Shape shape, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject jsonObject = new JsonObject();
        
        // Serialize Shape type
        jsonObject.addProperty("type", shape.getClass().getSimpleName());
        
        // Serialize specific fields based on type
        if (shape instanceof Circle) {
            jsonObject.addProperty("radius", ((Circle) shape).getRadius());
        } else if (shape instanceof Rectangle) {
            jsonObject.addProperty("width", ((Rectangle) shape).getWidth());
            jsonObject.addProperty("height", ((Rectangle) shape).getHeight());
        }
        
        return jsonObject;
    }
}

// Polymorphic Deserializer
class ShapeDeserializer implements JsonDeserializer<Shape> {
    @Override
    public Shape deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String type = jsonObject.get("type").getAsString();
        
        Shape shape = null;
        if (type.equals("Circle")) {
            shape = new Circle(jsonObject.get("radius").getAsDouble());
        } else if (type.equals("Rectangle")) {
            shape = new Rectangle(jsonObject.get("width").getAsDouble(), jsonObject.get("height").getAsDouble());
        }
        
        return shape;
    }
}

public class Main {
    public static void main(String[] args) {
        // Create instances of Circle and Rectangle
        Shape circle = new Circle(5.0);
        Shape rectangle = new Rectangle(4.0, 6.0);

        // Create Gson instance with custom serializers
        Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Shape.class, new ShapeSerializer())
                        .registerTypeAdapter(Shape.class, new ShapeDeserializer())
                        .create();

        // Serialize both Circle and Rectangle to JSON
        String circleJson = gson.toJson(circle);
        String rectangleJson = gson.toJson(rectangle);

        System.out.println("Serialized Circle: " + circleJson);
        System.out.println("Serialized Rectangle: " + rectangleJson);

        // Deserialize JSON back to objects
        Shape deserializedCircle = gson.fromJson(circleJson, Shape.class);
        Shape deserializedRectangle = gson.fromJson(rectangleJson, Shape.class);

        System.out.println("Deserialized Circle: " + deserializedCircle.getClass().getSimpleName());
        System.out.println("Deserialized Rectangle: " + deserializedRectangle.getClass().getSimpleName());
    }
}

ব্যাখ্যা:

  1. Shape ক্লাস: এটি একটি অ্যাবস্ট্রাক্ট বেস ক্লাস, যার মধ্যে একটি type ফিল্ড রয়েছে, যা সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করতে সহায়ক। এই ফিল্ডটি টাইপ ইনফরমেশন হিসেবে কাজ করবে।
  2. Circle এবং Rectangle ক্লাস: এগুলো Shape এর সাবক্লাস। তাদের বিভিন্ন প্রপার্টি (যেমন radius, width, height) রয়েছে যা নির্দিষ্ট ক্লাস অনুযায়ী JSON এ সিরিয়ালাইজ করা হবে।
  3. কাস্টম সিরিয়ালাইজার (ShapeSerializer): এই ক্লাসটি Shape অবজেক্টকে JSON-এ রূপান্তরিত করে। এটি প্রথমে type ফিল্ডের মান হিসেবে ক্লাসের নাম (যেমন Circle বা Rectangle) সিরিয়ালাইজ করে এবং তারপর সংশ্লিষ্ট ক্লাসের প্রপার্টিগুলি সিরিয়ালাইজ করে।
  4. কাস্টম ডেসিরিয়ালাইজার (ShapeDeserializer): এটি JSON ডেটা থেকে ডেসিরিয়ালাইজ করে এবং type ফিল্ডের উপর ভিত্তি করে সঠিক সাবক্লাসের অবজেক্ট তৈরি করে।

আউটপুট:

Serialized Circle: {"type":"Circle","radius":5.0}
Serialized Rectangle: {"type":"Rectangle","width":4.0,"height":6.0}
Deserialized Circle: Circle
Deserialized Rectangle: Rectangle

3. JSON স্ট্রাকচার:

Circle এর জন্য:

{
  "type": "Circle",
  "radius": 5.0
}

Rectangle এর জন্য:

{
  "type": "Rectangle",
  "width": 4.0,
  "height": 6.0
}

সারাংশ:

  • Polymorphic Serialization: একাধিক সাবক্লাসের জন্য একই বেস ক্লাসের সিরিয়ালাইজেশন করতে হলে, আপনাকে টাইপ ইনফরমেশন JSON এ যুক্ত করতে হবে। কাস্টম সিরিয়ালাইজার ব্যবহার করে আপনি এই কাজটি করতে পারেন।
  • Polymorphic Deserialization: JSON ডেটা থেকে সঠিক সাবক্লাসের অবজেক্ট ডেসিরিয়ালাইজ করতে, আপনি টাইপ ইনফরমেশন (যেমন type ফিল্ড) ব্যবহার করে কাস্টম ডেসিরিয়ালাইজার তৈরি করতে পারেন।
Content added By
Promotion

Are you sure to start over?

Loading...