@JsonDeserialize एनोटेशन का उपयोग JSON को जावा ऑब्जेक्ट में डीसीरियलाइज करते समय कस्टम डीसीरियलाइज़र घोषित करने के लिए किया जाता है। हम StdDeserializer क्लास को जेनेरिक टाइप Employee के साथ एक्सटेंड करके और StdDeserializer क्लास के deserialize() मेथड को ओवरराइड करके एक कस्टम डीसीरियलाइज़र इम्प्लीमेंट कर सकते हैं।
सिंटैक्स
@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonDeserialize
उदाहरण
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.deser.std.*;
public class JsonDeSerializeAnnotationTest {
public static void main(String[] args) throws JsonProcessingException, IOException {
Employee emp = new Employee(115, "Adithya");
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(emp);
emp = mapper.readValue(jsonString, Employee.class);
System.out.println(emp);
}
}
// CustomDeserializer क्लास
class CustomDeserializer extends StdDeserializer<Employee> {
public CustomDeserializer(Class<Employee> t) {
super(t);
}
public CustomDeserializer() {
this(Employee.class);
}
@Override
public Employee deserialize(JsonParser jp, DeserializationContext dc)
throws IOException, JsonProcessingException {
int id = 0;
String name = null;
JsonToken currentToken = null;
while((currentToken = jp.nextValue()) != null) {
switch(currentToken) {
case VALUE_NUMBER_INT:
if(jp.getCurrentName().equals("id")) {
id = jp.getIntValue();
}
break;
case VALUE_STRING:
switch(jp.getCurrentName()) {
case "name":
name = jp.getText();
break;
default:
break;
}
break;
default:
break;
}
}
return new Employee(id, name);
}
}
// Employee क्लास
@JsonDeserialize(using=CustomDeserializer.class)
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public String getName() { return name; }
@Override
public String toString() {
return "ID: " + this.id + "\nName: " + this.name;
}
}
आउटपुट
ID: 115
Name: Adithya
कस्टम डीसीरियलाइज़र के मुख्य घटक
- JsonParser: JSON टोकन्स को पढ़ने के लिए (nextToken(), getText(), getIntValue(), आदि)
- DeserializationContext: कॉन्फिगरेशन, कैश, अन्य डीसीरियलाइज़र्स तक पहुंच के लिए
- JsonToken: करंट टोकन टाइप (VALUE_STRING, VALUE_NUMBER_INT, START_OBJECT, आदि)
उन्नत उपयोग
// कंस्ट्रक्टर पैरामीटर्स के साथ
@JsonDeserialize(using = CustomDeserializer.class)
public class Employee {
@JsonCreator
public Employee(@JsonProperty("id") int id, @JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
}
// कलेक्शन के लिए
@JsonDeserialize(contentUsing = CustomItemDeserializer.class)
List<Item> items;
कब उपयोग करें
- JSON स्ट्रक्चर जावा क्लास स्ट्रक्चर से मेल नहीं खाता
- कॉम्प्लेक्स डेटा ट्रांसफॉर्मेशन आवश्यक हो
- लीगेसी/थर्ड-पार्टी JSON फॉर्मेट को हैंडल करना हो
- कंडीशनल डीसीरियलाइजेशन लॉजिक चाहिए