@JsonProperty Annotation

Java Technologies - জ্যাকসন অ্যানোটেশন (Jackson Annotations)
183

@JsonProperty Jackson এর একটি গুরুত্বপূর্ণ অ্যানোটেশন, যা JSON Serialization এবং Deserialization-এর সময় ফিল্ডের নাম কাস্টমাইজ করতে ব্যবহার করা হয়। এটি ক্লাসের ফিল্ড বা মেথডে প্রয়োগ করা যায়।


@JsonProperty Annotation এর বৈশিষ্ট্য

  1. Custom JSON Field Name:
    • Java ফিল্ডের নাম এবং JSON ফিল্ডের নাম ভিন্ন হতে পারে। @JsonProperty ব্যবহার করে JSON ফিল্ডের নাম নির্ধারণ করা যায়।
  2. Serialization এবং Deserialization Control:
    • JSON Serialization এবং Deserialization উভয়ের জন্য ফিল্ডের নাম নির্ধারণ করতে সাহায্য করে।
  3. Required Field Validation:
    • JSON থেকে ফিল্ড অনুপস্থিত থাকলে @JsonProperty(required = true) দিয়ে Validation নিশ্চিত করা যায়।
  4. Index Mapping:
    • JSON Arrays-এর ক্ষেত্রে Index নির্ধারণ করা যায়।

@JsonProperty এর উদাহরণ

১. Custom Field Name

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    @JsonProperty("user_id")
    private int id;

    @JsonProperty("full_name")
    private String name;

    private String email;

    // Getters and Setters
}
Serialization Example:
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyExample {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setId(1);
        user.setName("Rahim");
        user.setEmail("rahim@example.com");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);

        System.out.println(json);
    }
}
JSON Output:
{
  "user_id": 1,
  "full_name": "Rahim",
  "email": "rahim@example.com"
}

২. Required Field Validation

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    @JsonProperty(required = true)
    private int id;

    @JsonProperty(required = true)
    private String name;

    private String email;

    // Getters and Setters
}
Deserialization Example:
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyExample {
    public static void main(String[] args) {
        String json = "{\"id\":1}"; // `name` ফিল্ড নেই

        try {
            ObjectMapper mapper = new ObjectMapper();
            User user = mapper.readValue(json, User.class);
            System.out.println(user);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Error Output:
Error: Missing required creator property 'name' (index 1)

৩. Constructor এর ক্ষেত্রে @JsonProperty ব্যবহার

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    private int id;
    private String name;
    private String email;

    public User(@JsonProperty("user_id") int id, 
                @JsonProperty("full_name") String name, 
                @JsonProperty("email_address") String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Getters
}
Deserialization Example:
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyExample {
    public static void main(String[] args) throws Exception {
        String json = "{\"user_id\":1,\"full_name\":\"Rahim\",\"email_address\":\"rahim@example.com\"}";

        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);

        System.out.println(user.getName()); // Output: Rahim
    }
}

৪. @JsonProperty এর মাধ্যমে Index Mapping

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    @JsonProperty(index = 1)
    private int id;

    @JsonProperty(index = 2)
    private String name;

    @JsonProperty(index = 3)
    private String email;

    // Getters and Setters
}
Serialization Example:
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyExample {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setId(1);
        user.setName("Rahim");
        user.setEmail("rahim@example.com");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);

        System.out.println(json);
    }
}
JSON Output:
{
  "id": 1,
  "name": "Rahim",
  "email": "rahim@example.com"
}

@JsonProperty এর গুরুত্বপূর্ণ ব্যবহার

  1. API Contract নির্ধারণ:
    • REST API-এর জন্য নির্দিষ্ট JSON ফিল্ড নাম নিশ্চিত করতে ব্যবহার করা হয়।
  2. Backward Compatibility:
    • ফিল্ড নাম পরিবর্তনের পরও পূর্বের JSON ফরম্যাট সমর্থন করা যায়।
  3. Deserialization Issue সমাধান:
    • JSON ফিল্ডের ভিন্ন নাম বা অনুপস্থিত ফিল্ড সমস্যার সমাধানে কার্যকর।

  • @JsonProperty ব্যবহার করে JSON ফিল্ডের নাম কাস্টমাইজ এবং কনট্রোল করা যায়।
  • এটি Serialization/Deserialization-এর জন্য আরও নির্ভুল এবং গঠনগত JSON তৈরি করতে সাহায্য করে।
  • API উন্নয়ন এবং JSON ফরম্যাট নিয়ন্ত্রণে এটি অত্যন্ত কার্যকর একটি অ্যানোটেশন।
Content added By

@JsonProperty এর ধারণা এবং ব্যবহার

192

@JsonProperty হল Jackson এর একটি গুরুত্বপূর্ণ অ্যানোটেশন, যা JSON serialization এবং deserialization এর সময় Java ফিল্ড বা মেথডের নাম কাস্টমাইজ করতে ব্যবহৃত হয়। এটি JSON ডেটার সাথে Java ফিল্ডের ম্যাপিং নিয়ন্ত্রণ করে।


মূল ধারণা

  1. Custom Property Name:
    • JSON ফিল্ডের নাম এবং Java ফিল্ডের নাম ভিন্ন হলে তাদের মধ্যে ম্যাপিং করার জন্য @JsonProperty ব্যবহার করা হয়।
  2. Serialization এবং Deserialization Control:
    • JSON থেকে Java Object (deserialization) এবং Java Object থেকে JSON (serialization) করার সময় নির্দিষ্ট নামের নিয়ন্ত্রণ।
  3. Optional Properties:
    • এটি value এর মাধ্যমে একটি JSON ফিল্ডকে নির্দিষ্ট Java ফিল্ডে ম্যাপ করে।
  4. Constructor Parameters:
    • কন্সট্রাক্টরের প্যারামিটারের সাথে JSON ফিল্ড ম্যাপিং করার জন্যও এটি ব্যবহৃত হয়।

ব্যবহার পদ্ধতি

1. JSON Field এবং Java Field এর ভিন্ন নাম

যদি JSON ফিল্ড এবং Java ফিল্ডের নাম ভিন্ন হয়, তাহলে @JsonProperty ব্যবহার করতে হবে।

কোড উদাহরণ
import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    @JsonProperty("full_name") // Map JSON field "full_name" to Java field "name"
    private String name;

    @JsonProperty("years") // Map JSON field "years" to Java field "age"
    private int age;

    // Constructor, Getters, Setters
    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}
Serialization Example (Object to JSON)
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // Create object
        Person person = new Person("John Doe", 30);

        // Serialize to JSON
        String json = mapper.writeValueAsString(person);
        System.out.println(json); // Output: {"full_name":"John Doe","years":30}
    }
}
Deserialization Example (JSON to Object)
String json = "{\"full_name\":\"Jane Doe\",\"years\":25}";
Person person = mapper.readValue(json, Person.class);
System.out.println(person.getName() + " - " + person.getAge()); // Output: Jane Doe - 25

2. Constructor Parameter Mapping

@JsonProperty ব্যবহার করে JSON ডেটা থেকে কন্সট্রাক্টরের প্যারামিটারে ডেটা ম্যাপ করা যায়।

কোড উদাহরণ
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    private String name;
    private int age;

    @JsonCreator
    public Person(@JsonProperty("full_name") String name, @JsonProperty("years") int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
Deserialization Example
String json = "{\"full_name\":\"Jane Doe\",\"years\":25}";
Person person = mapper.readValue(json, Person.class);
System.out.println(person.getName() + " - " + person.getAge()); // Output: Jane Doe - 25

3. Control Visibility (Read-Only or Write-Only Fields)

@JsonProperty এর মাধ্যমে JSON serialization বা deserialization কে সীমাবদ্ধ করা যায়।

কোড উদাহরণ
import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    private String name;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY) // Serialize only, no deserialization
    private int age;

    // Constructor, Getters, Setters
}
Explanation
  • READ_ONLY: JSON থেকে Object তৈরি করা যাবে না, কিন্তু Object থেকে JSON তৈরি করা যাবে।
  • WRITE_ONLY: JSON থেকে Object তৈরি করা যাবে, কিন্তু Object থেকে JSON তৈরি করা যাবে না।

4. Default Values for Missing JSON Fields

@JsonProperty এবং @JsonSetter ব্যবহার করে JSON ডেটাতে একটি ফিল্ড মিসিং থাকলে ডিফল্ট মান সেট করা যায়।

কোড উদাহরণ
import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    private String name;

    @JsonProperty(defaultValue = "25") // Default value for age
    private int age;

    // Constructor, Getters, Setters
}

উপকারিতা

  1. Custom JSON Mapping:
    • JSON এবং Java ফিল্ডের মধ্যে নামকরণের পার্থক্য সমাধান করা।
  2. Flexible Serialization/Deserialization:
    • Read-only এবং Write-only ফিল্ড ব্যবস্থাপনা সহজ।
  3. Constructor Integration:
    • কন্সট্রাক্টরের প্যারামিটার ম্যাপিং সহজতর করে।
  4. Default Values:
    • JSON ডেটা মিসিং হলে ডিফল্ট মান প্রদান।

সতর্কতা

  • @JsonProperty ভুলভাবে ব্যবহার করলে JSON serialization এবং deserialization ব্যর্থ হতে পারে।
  • Constructor parameter mapping এর সময় সঠিক JSON key ব্যবহার করতে হবে।

@JsonProperty Jackson এর অন্যতম গুরুত্বপূর্ণ অ্যানোটেশন, যা JSON serialization এবং deserialization এর সময় Java ফিল্ড বা মেথডের নাম কাস্টমাইজ করতে ব্যবহৃত হয়। এটি REST API, Microservices, এবং JSON ডেটা প্রক্রিয়াকরণের ক্ষেত্রে অত্যন্ত কার্যকর।

Content added By

Properties এর নাম পরিবর্তন করা (serialization এবং deserialization)

178

Jackson JSON সিরিয়ালাইজ এবং ডেসিরিয়ালাইজ করার সময় Java Object এর properties এর নাম JSON properties এর সাথে ম্যাপ করতে পারে। তবে, কখনো কখনো JSON ফিল্ডের নাম এবং Java ফিল্ডের নাম ভিন্ন হতে পারে। এই ধরনের ক্ষেত্রে Jackson অ্যানোটেশন ব্যবহার করে properties-এর নাম পরিবর্তন করা যায়।


@JsonProperty অ্যানোটেশন

@JsonProperty অ্যানোটেশন ব্যবহার করে Java ফিল্ড এবং JSON ফিল্ডের মধ্যে একটি কাস্টম নাম ম্যাপিং নির্ধারণ করা যায়। এটি serialization (object → JSON) এবং deserialization (JSON → object) উভয় প্রক্রিয়ার সময় কাজ করে।


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

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

class User {
    @JsonProperty("user_name")
    private String name;

    @JsonProperty("user_age")
    private int age;

    public User() {} // Default constructor is required for deserialization

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters and Setters
    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 class JsonPropertyExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // Serialization: Object → JSON
        User user = new User("Alice", 25);
        String json = mapper.writeValueAsString(user);
        System.out.println("Serialized JSON: " + json);

        // Deserialization: JSON → Object
        String inputJson = "{\"user_name\":\"Bob\",\"user_age\":30}";
        User deserializedUser = mapper.readValue(inputJson, User.class);
        System.out.println("Deserialized User: " + deserializedUser.getName() + ", Age: " + deserializedUser.getAge());
    }
}

Output:

Serialized JSON: {"user_name":"Alice","user_age":25}
Deserialized User: Bob, Age: 30

@JsonAlias: Alternative Names for Deserialization

@JsonAlias অ্যানোটেশন ব্যবহার করে একটি ফিল্ডের জন্য একাধিক বিকল্প নাম নির্ধারণ করা যায়। এটি মূলত deserialization এর জন্য কার্যকর।

উদাহরণ:
import com.fasterxml.jackson.annotation.JsonAlias;

class User {
    @JsonAlias({"user_name", "username", "userName"})
    private String name;

    private int age;

    // Getters and Setters
}
Input JSON:
{
  "username": "Alice",
  "age": 25
}
Output:
Deserialized User: Alice, Age: 25

Global Configuration for Field Naming

Jackson-এর PropertyNamingStrategy ব্যবহার করে সমস্ত ফিল্ডের নাম পরিবর্তন করা সম্ভব। এটি snake_case, kebab-case, বা কাস্টম স্টাইল সেট করার জন্য কার্যকর।

Snake Case Naming Strategy:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;

public class SnakeCaseExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

        User user = new User("Alice", 25);
        String json = mapper.writeValueAsString(user);
        System.out.println("Serialized JSON (Snake Case): " + json);
    }
}
Serialized Output:
{"name":"Alice","age":25}

Custom Serialization এবং Deserialization

কাস্টম সিরিয়ালাইজার বা ডেসিরিয়ালাইজার ব্যবহার করেও properties-এর নাম পরিবর্তন করা যায়।

Custom Serializer উদাহরণ:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class CustomUserSerializer extends StdSerializer<User> {
    public CustomUserSerializer() {
        super(User.class);
    }

    @Override
    public void serialize(User user, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("custom_name", user.getName());
        gen.writeNumberField("custom_age", user.getAge());
        gen.writeEndObject();
    }
}

Custom Deserializer উদাহরণ:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class CustomUserDeserializer extends StdDeserializer<User> {
    public CustomUserDeserializer() {
        super(User.class);
    }

    @Override
    public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        String name = node.get("custom_name").asText();
        int age = node.get("custom_age").asInt();
        return new User(name, age);
    }
}

Configuration:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(User.class, new CustomUserSerializer());
module.addDeserializer(User.class, new CustomUserDeserializer());
mapper.registerModule(module);

সারাংশ

অ্যানোটেশন/কৌশলব্যবহার
@JsonPropertyJSON ফিল্ডের নাম এবং Java ফিল্ডের নাম কাস্টমাইজ করা।
@JsonAliasDeserialization-এর জন্য একাধিক বিকল্প নাম ব্যবহার।
PropertyNamingStrategyপুরো ফিল্ড নামকরণ স্ট্র্যাটেজি (যেমন, snake_case, kebab-case)।
Custom Serializer/Deserializerসম্পূর্ণ কাস্টম নিয়ম সংজ্ঞায়িত করার জন্য।

  1. @JsonProperty এবং @JsonAlias অ্যানোটেশন সহজ এবং কার্যকর সমাধান।
  2. PropertyNamingStrategy বড় প্রজেক্টের ক্ষেত্রে গ্লোবাল কনফিগারেশন প্রদান করে।
  3. কাস্টম নিয়মের প্রয়োজন হলে Custom Serializer/Deserializer ব্যবহার করতে হবে।

এই টুলগুলো ব্যবহার করে JSON ফিল্ড এবং Java properties-এর মধ্যে নির্ভুল এবং কার্যকর ম্যাপিং নিশ্চিত করা যায়।

Content added By

Optional Properties এবং Default Values সেট করা

188

Jackson লাইব্রেরি JSON serialization এবং deserialization-এর ক্ষেত্রে Optional Properties এবং Default Values সেট করার জন্য সহজ এবং কার্যকর পদ্ধতি সরবরাহ করে। এটি ডাইনামিক এবং কাঠামোবিহীন JSON হ্যান্ডল করতে সাহায্য করে। নিচে এই বিষয়গুলোর বিস্তারিত ব্যাখ্যা করা হলো।


1. Optional Properties হ্যান্ডল করা

1.1 @JsonIgnoreProperties

  • JSON-এ থাকা অপ্রয়োজনীয় বা অতিরিক্ত প্রপার্টি হ্যান্ডল করতে ব্যবহার করা হয়।
  • অজানা প্রপার্টিগুলোকে উপেক্ষা করতে ignoreUnknown = true ব্যবহার করা হয়।

উদাহরণ:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private String name;
    private int age;

    // Getters and Setters
}

JSON ইনপুট:

{
  "name": "Alice",
  "age": 25,
  "unknownProperty": "value"
}

আউটপুট:

Deserialized User: User{name='Alice', age=25}

1.2 Optional ফিল্ডের জন্য Default Values সেট করা

@JsonSetter এবং @JsonProperty

উদাহরণ ১: Default Values সহ Optional Properties

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    private String name;

    @JsonProperty(defaultValue = "18")
    private int age;

    // Getters and Setters
}

JSON ইনপুট (age অনুপস্থিত):

{
  "name": "Alice"
}

আউটপুট:

Deserialized User: User{name='Alice', age=18}

1.3 Null বা অনুপস্থিত প্রপার্টি হ্যান্ডল করা

@JsonInclude: Optional Properties বাদ দেওয়া

@JsonInclude ব্যবহার করে null বা অনুপস্থিত প্রপার্টিগুলো serialization-এর সময় বাদ দেওয়া যায়।

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
    private String name;
    private String email;

    // Getters and Setters
}

JSON আউটপুট (email=null):

{
  "name": "Alice"
}

2. Default Values সেট করার পদ্ধতি

2.1 Constructor-based Default Values

Constructor ব্যবহার করে Optional Properties-এর জন্য Default Value সেট করা যায়।

উদাহরণ:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    private String name;
    private int age;

    @JsonCreator
    public User(@JsonProperty("name") String name, @JsonProperty("age") Integer age) {
        this.name = name;
        this.age = (age != null) ? age : 18; // Default Value
    }

    // Getters and Setters
}

JSON ইনপুট (age অনুপস্থিত):

{
  "name": "Alice"
}

আউটপুট:

Deserialized User: User{name='Alice', age=18}

2.2 Optional এবং Default Value Handling with @JsonSetter

@JsonSetter দিয়ে Null প্রপার্টির জন্য Default Value সেট করা যায়।

উদাহরণ:

import com.fasterxml.jackson.annotation.JsonSetter;

public class User {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    @JsonSetter
    public void setAge(Integer age) {
        this.age = (age != null) ? age : 18; // Default Value
    }

    public int getAge() {
        return age;
    }
}

JSON ইনপুট:

{
  "name": "Alice"
}

আউটপুট:

Deserialized User: User{name='Alice', age=18}

2.3 Default Values with @JsonDeserialize

Custom Deserializer ব্যবহার করে Default Values সেট করা সম্ভব।

উদাহরণ:

import com.fasterxml.jackson.annotation.JsonDeserialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private String name;
    private int age;

    // Getters and Setters
}

Custom Deserializer:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {
    @Override
    public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        String name = node.get("name").asText();
        int age = node.has("age") ? node.get("age").asInt() : 18; // Default Value
        return new User(name, age);
    }
}

3. Optional Properties এবং Default Values Handling-এর Industry Standards

3.1 Avoid Hardcoding Defaults

  • Optional Properties-এর জন্য ডিফল্ট ভ্যালু সরাসরি Constructor বা Setter-এ রাখুন।

3.2 Use Annotations for Simple Cases

  • @JsonProperty(defaultValue) এবং @JsonSetter ছোট প্রোজেক্টে ব্যবহার করুন।
  • জটিল লজিকের জন্য Custom Deserializer ব্যবহার করুন।

3.3 Include Only Necessary Fields

  • @JsonInclude দিয়ে serialization-এর সময় null বা optional ফিল্ড বাদ দিন।

3.4 Handle Unknown Fields Gracefully

  • @JsonIgnoreProperties(ignoreUnknown = true) ব্যবহার করে অজানা প্রপার্টি হ্যান্ডল করুন।

3.5 Consistent JSON API Design

  • API ডেভেলপমেন্টে Optional Properties এবং Default Values ক্লিয়ারলি ডকুমেন্ট করুন।

4. উদাহরণ: Full Implementation

User Class:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    @JsonProperty(defaultValue = "Guest")
    private String name;

    @JsonProperty(defaultValue = "18")
    private int age;

    // Getters and Setters
}

Serialization এবং Deserialization:

import com.fasterxml.jackson.databind.ObjectMapper;

public class DefaultValuesExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // Deserialize JSON
        String json = "{\"name\":\"Alice\"}";
        User user = mapper.readValue(json, User.class);
        System.out.println("Deserialized User: " + user.getName() + ", Age: " + user.getAge());

        // Serialize Object
        String serializedJson = mapper.writeValueAsString(user);
        System.out.println("Serialized JSON: " + serializedJson);
    }
}

আউটপুট:

Deserialized User: Alice, Age: 18
Serialized JSON: {"name":"Alice","age":18}

Jackson-এ Optional Properties এবং Default Values সেট করার জন্য বিভিন্ন পদ্ধতি রয়েছে। @JsonProperty(defaultValue) এবং @JsonSetter ছোট এবং সহজ সমাধান প্রদান করে। বড় এবং জটিল প্রোজেক্টের ক্ষেত্রে Custom Deserializer ব্যবহার করে আরও ভালো কন্ট্রোল পাওয়া যায়। Industry Standards মেনে কাজ করলে কোড আরও রিডেবল, মেনটেইনেবল, এবং পারফরম্যান্ট হবে।

Content added By

Practical উদাহরণ সহ @JsonProperty এর ব্যবহার

213

@JsonProperty একটি Jackson অ্যানোটেশন যা JSON এবং Java Object এর ফিল্ডগুলির মধ্যে কাস্টম নাম বা ম্যাপিং সম্পর্ক তৈরি করতে ব্যবহৃত হয়। এটি মূলত JSON ডেটার প্রপার্টি এবং Java ফিল্ডের মধ্যে পারস্পরিক নাম ভিন্ন থাকলে সেগুলিকে সংযোগ করার জন্য ব্যবহার করা হয়।


@JsonProperty এর কার্যকারিতা

  1. JSON প্রপার্টি এবং Java ফিল্ডের মধ্যে কাস্টম নামকরণ।
  2. JSON সিরিয়ালাইজেশন এবং ডেসিরিয়ালাইজেশনে নির্দিষ্ট ফিল্ড ম্যাপিং।
  3. ডেসিরিয়ালাইজেশনের সময় প্রয়োজনীয় ফিল্ড নির্ধারণ করা।

@JsonProperty এর Practical উদাহরণ

১. কাস্টম নাম ম্যাপিং

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    @JsonProperty("user_id")
    private int id;

    @JsonProperty("user_name")
    private String name;

    @JsonProperty("user_email")
    private String email;

    // 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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

JSON Input:

{
    "user_id": 1,
    "user_name": "John Doe",
    "user_email": "john.doe@example.com"
}

Usage Example:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyExample {
    public static void main(String[] args) throws Exception {
        String json = "{ \"user_id\": 1, \"user_name\": \"John Doe\", \"user_email\": \"john.doe@example.com\" }";

        ObjectMapper objectMapper = new ObjectMapper();

        // JSON থেকে Object এ রূপান্তর
        User user = objectMapper.readValue(json, User.class);
        System.out.println("User Name: " + user.getName());

        // Object থেকে JSON এ রূপান্তর
        String serializedJson = objectMapper.writeValueAsString(user);
        System.out.println("Serialized JSON: " + serializedJson);
    }
}

আউটপুট:

User Name: John Doe
Serialized JSON: {"user_id":1,"user_name":"John Doe","user_email":"john.doe@example.com"}

২. ফিল্ড রেনেমিং

যদি JSON প্রপার্টির নাম Java ফিল্ডের নামের সাথে মেলে না, তবে @JsonProperty ব্যবহার করা হয়।

public class Employee {
    @JsonProperty("empId")
    private int id;

    @JsonProperty("empName")
    private String name;

    @JsonProperty("department")
    private String dept;

    // Getters and Setters
}

JSON Input:

{
    "empId": 101,
    "empName": "Alice",
    "department": "Engineering"
}

JSON Output:

{
    "empId": 101,
    "empName": "Alice",
    "department": "Engineering"
}

৩. JSON সিরিয়ালাইজেশন এবং ডেসিরিয়ালাইজেশনে অর্ডার কাস্টমাইজ করা

@JsonProperty এর index অ্যাট্রিবিউট ব্যবহার করে সিরিয়ালাইজেশনের সময় JSON প্রপার্টির ক্রম নির্ধারণ করা যায়।

import com.fasterxml.jackson.annotation.JsonProperty;

public class Product {
    @JsonProperty(value = "product_id", index = 1)
    private int id;

    @JsonProperty(value = "product_name", index = 2)
    private String name;

    @JsonProperty(value = "product_price", index = 3)
    private double price;

    // Getters and Setters
}

Usage Example:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPropertyOrderExample {
    public static void main(String[] args) throws Exception {
        Product product = new Product();
        product.setId(101);
        product.setName("Laptop");
        product.setPrice(750.50);

        ObjectMapper objectMapper = new ObjectMapper();

        // Object থেকে JSON
        String json = objectMapper.writeValueAsString(product);
        System.out.println("Serialized JSON: " + json);
    }
}

JSON Output:

{
    "product_id": 101,
    "product_name": "Laptop",
    "product_price": 750.5
}

৪. ফিল্ডকে "required" হিসেবে চিহ্নিত করা

JSON ডেসিরিয়ালাইজেশনের সময় ফিল্ড প্রয়োজনীয় কিনা তা নির্ধারণ করতে required অ্যাট্রিবিউট ব্যবহার করা যায়।

import com.fasterxml.jackson.annotation.JsonProperty;

public class Account {
    @JsonProperty(value = "account_id", required = true)
    private int id;

    @JsonProperty("account_name")
    private String name;

    // Getters and Setters
}

Usage Example:

public class JsonPropertyRequiredExample {
    public static void main(String[] args) {
        String json = "{ \"account_name\": \"Savings\" }"; // Missing account_id

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Account account = objectMapper.readValue(json, Account.class);
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Error Output:

Error: Missing required creator property 'account_id' (index 0)

@JsonProperty ব্যবহার করার মাধ্যমে:

  1. JSON এবং Java ফিল্ডের মধ্যে কাস্টম নামকরণ বা ম্যাপিং করা যায়।
  2. প্রপার্টি অর্ডার, রেনেমিং এবং প্রয়োজনীয় ফিল্ড নির্ধারণ করা সহজ হয়।
  3. এটি JSON ডেটা প্রসেসিংকে আরও নমনীয় ও কার্যকর করে তোলে।

উপযুক্ত ক্ষেত্রে: RESTful API-এর মাধ্যমে JSON ডেটা আদান-প্রদান এবং কাস্টম ডেটা ফরম্যাটিং নিশ্চিত করার জন্য এটি অত্যন্ত গুরুত্বপূর্ণ।

Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...