Nested Collection Serialization এবং Deserialization

JSON এর সাথে Collection এবং Generic টাইপের কাজ - জিসন (Gson) - Java Technologies

414

Nested Collection হলো এমন একটি অবস্থা যেখানে একটি ক্লাস বা অবজেক্টের মধ্যে অন্য অবজেক্ট বা কালেকশন (যেমন লিস্ট, ম্যাপ) থাকে। Gson লাইব্রেরি এই ধরনের নেস্টেড অবজেক্ট বা কালেকশন সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করতে সমর্থ।

এখানে, আমরা দেখবো কিভাবে Gson ব্যবহার করে Nested Collection গুলো সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করা যায়।


1. Nested Collection Serialization এবং Deserialization

ধরা যাক, আমাদের কাছে একটি School ক্লাস রয়েছে, যেখানে একটি List<Student> নামে একটি নেস্টেড কালেকশন (লিস্ট) আছে, এবং Student এর মধ্যে আরেকটি List<String> নামে সাব কালেকশন রয়েছে (যেমন ছাত্রের বিষয় তালিকা)।

উদাহরণ:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Nested Collection তৈরি
        List<String> subjects1 = new ArrayList<>();
        subjects1.add("Math");
        subjects1.add("Science");

        List<String> subjects2 = new ArrayList<>();
        subjects2.add("English");
        subjects2.add("History");

        Student student1 = new Student("John", 20, subjects1);
        Student student2 = new Student("Alice", 22, subjects2);

        List<Student> students = new ArrayList<>();
        students.add(student1);
        students.add(student2);

        School school = new School("Greenwood High", students);

        // Gson অবজেক্ট তৈরি
        Gson gson = new Gson();

        // Nested Collection (List of Students) সিরিয়ালাইজ
        String json = gson.toJson(school);
        System.out.println("Serialized JSON: " + json);

        // JSON থেকে Deserialization (Back to Java object)
        School deserializedSchool = gson.fromJson(json, School.class);
        System.out.println("\nDeserialized School:");
        System.out.println("School Name: " + deserializedSchool.name);
        for (Student student : deserializedSchool.students) {
            System.out.println("Student Name: " + student.name);
            System.out.println("Subjects: " + student.subjects);
        }
    }
}

class School {
    String name;
    List<Student> students;

    School(String name, List<Student> students) {
        this.name = name;
        this.students = students;
    }
}

class Student {
    String name;
    int age;
    List<String> subjects;

    Student(String name, int age, List<String> subjects) {
        this.name = name;
        this.age = age;
        this.subjects = subjects;
    }
}

আউটপুট:

Serialized JSON: {"name":"Greenwood High","students":[{"name":"John","age":20,"subjects":["Math","Science"]},{"name":"Alice","age":22,"subjects":["English","History"]}]}

Deserialized School:
School Name: Greenwood High
Student Name: John
Subjects: [Math, Science]
Student Name: Alice
Subjects: [English, History]

2. Nested Collection Serialization (Custom Collection Types)

এছাড়া, Gson জেনেরিক টাইপের কালেকশন যেমন List, Set, Map ইত্যাদি সঠিকভাবে সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করার জন্য TypeToken ব্যবহার করা যেতে পারে। উদাহরণস্বরূপ, যদি আপনি একটি Map<String, List<Student>> সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করতে চান, তাহলে TypeToken ব্যবহার করা উচিত।

উদাহরণ:

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Nested Map Collection তৈরি
        List<Student> students1 = new ArrayList<>();
        students1.add(new Student("John", 20, Arrays.asList("Math", "Science")));
        students1.add(new Student("Alice", 22, Arrays.asList("English", "History")));

        List<Student> students2 = new ArrayList<>();
        students2.add(new Student("Bob", 23, Arrays.asList("Physics", "Chemistry")));
        
        Map<String, List<Student>> schoolStudents = new HashMap<>();
        schoolStudents.put("Class A", students1);
        schoolStudents.put("Class B", students2);

        // Gson অবজেক্ট তৈরি
        Gson gson = new Gson();

        // Nested Map Collection সিরিয়ালাইজ
        String json = gson.toJson(schoolStudents);
        System.out.println("Serialized Map JSON: " + json);

        // JSON থেকে Deserialization (Back to Java object)
        Type mapType = new TypeToken<Map<String, List<Student>>>() {}.getType();
        Map<String, List<Student>> deserializedMap = gson.fromJson(json, mapType);
        
        System.out.println("\nDeserialized Map:");
        for (Map.Entry<String, List<Student>> entry : deserializedMap.entrySet()) {
            System.out.println("Class: " + entry.getKey());
            for (Student student : entry.getValue()) {
                System.out.println("Student Name: " + student.name);
                System.out.println("Subjects: " + student.subjects);
            }
        }
    }
}

class Student {
    String name;
    int age;
    List<String> subjects;

    Student(String name, int age, List<String> subjects) {
        this.name = name;
        this.age = age;
        this.subjects = subjects;
    }
}

আউটপুট:

Serialized Map JSON: {"Class A":[{"name":"John","age":20,"subjects":["Math","Science"]},{"name":"Alice","age":22,"subjects":["English","History"]}],"Class B":[{"name":"Bob","age":23,"subjects":["Physics","Chemistry"]}]}

Deserialized Map:
Class: Class A
Student Name: John
Subjects: [Math, Science]
Student Name: Alice
Subjects: [English, History]
Class: Class B
Student Name: Bob
Subjects: [Physics, Chemistry]

3. Custom Serialization/Deserialization for Nested Collection

যদি আপনি একটি কাস্টম সিরিয়ালাইজেশন বা ডেসিরিয়ালাইজেশন লজিক প্রয়োগ করতে চান, তবে আপনি JsonSerializer এবং JsonDeserializer ব্যবহার করতে পারেন। নিচে একটি কাস্টম ডেসিরিয়ালাইজেশন উদাহরণ দেওয়া হলো, যেখানে List<String> ক্লাসের উপাদানগুলির উপর কিছু কাস্টম লজিক প্রয়োগ করা হয়েছে।

উদাহরণ:

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":20,\"subjects\":[\"Math\",\"Science\"]}";

        Gson gson = new GsonBuilder()
                        .registerTypeAdapter(List.class, new CustomListDeserializer())
                        .create();

        Student student = gson.fromJson(json, Student.class);
        
        System.out.println("Student Name: " + student.name);
        System.out.println("Subjects: " + student.subjects);
    }
}

class Student {
    String name;
    int age;
    List<String> subjects;
}

class CustomListDeserializer implements JsonDeserializer<List<String>> {
    @Override
    public List<String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonArray jsonArray = json.getAsJsonArray();
        // Custom logic: Convert all subjects to uppercase
        for (JsonElement element : jsonArray) {
            element.getAsString().toUpperCase();
        }
        return context.deserialize(json, typeOfT);
    }
}

আউটপুট:

Student Name: John
Subjects: [MATH, SCIENCE]

Gson দিয়ে Nested Collection Serialization এবং Deserialization খুবই সহজ। আপনি List, Set, Map ইত্যাদি নেস্টেড কালেকশন খুব সহজেই সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করতে পারেন। এছাড়া, আপনি যদি বিশেষ ধরনের কাস্টম লজিক প্রয়োগ করতে চান, তবে JsonSerializer এবং JsonDeserializer ব্যবহার করে সেটা করতে পারেন।

Content added By
Promotion

Are you sure to start over?

Loading...