@JsonUnwrapped एनोटेशन का उपयोग सीरियलाइजेशन और डीसीरियलाइजेशन प्रक्रिया के दौरान वैल्यूज को अनरैप करने के लिए किया जा सकता है। यह एक कम्पोज्ड क्लास के वैल्यूज को रेंडर करने में मदद करता है जैसे कि वे पैरेंट क्लास से संबंधित हों।
सिंटैक्स
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonUnwrapped
उदाहरण
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonUnwrappedAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employee());
System.out.println(jsonString);
}
}
class Employee {
public int empId = 110;
public String empName = "Raja Ramesh";
@JsonUnwrapped
public Address address = new Address();
// Address क्लास
public static class Address {
public String doorNumber = "1118";
public String street = "madhapur";
public String pinCode = "500081";
public String city = "Hyderabad";
}
}
आउटपुट
{
"empId" : 110,
"empName" : "Raja Ramesh",
"doorNumber" : "1118",
"street" : "madhapur",
"pinCode" : "500081",
"city" : "Hyderabad"
}
बिना @JsonUnwrapped के आउटपुट
{
"empId" : 110,
"empName" : "Raja Ramesh",
"address" : {
"doorNumber" : "1118",
"street" : "madhapur",
"pinCode" : "500081",
"city" : "Hyderabad"
}
}
उपयोग के मामले
- फ्लैट JSON स्ट्रक्चर: जब नेस्टेड ऑब्जेक्ट को फ्लैट JSON में बदलना हो
- लीगेसी API कम्पैटिबिलिटी: जब एक्सटर्नल सिस्टम फ्लैट JSON एक्सपेक्ट करता हो
- डेटाबेस मैपिंग: जब एम्बेडेड एंटिटी के फील्ड्स को मेन टेबल में मैप करना हो
ध्यान देने योग्य बातें
- यदि पैरेंट और चाइल्ड दोनों में समान नाम के फील्ड्स हों तो कन्फ्लिक्ट हो सकता है
- डीसीरियलाइजेशन के समय भी यह काम करता है - फ्लैट JSON से नेस्टेड ऑब्जेक्ट बनाता है
- @JsonUnwrapped(prefix="addr.") का उपयोग करके प्रीफिक्स जोड़ा जा सकता है ताकि नाम कन्फ्लिक्ट से बचा जा सके