"Welcome To Ashok IT" "Spring Boot & Microservices" Topic : Serialization - Deserialization Date : 20/12/2024 (Session - 89) _____________________________________________________________________________________________________________________________ Last Session ============= * We are in discussion about XML related Marshalling - -UnMarhsalling Process. Today Session ============= JSON ==== * JSON Stands for JavaScript Object Notation * JSON is derived from JavaSCript but it is not part of JavaScript. * JSON is Interoperable Data Exchange Format between Applications. * JSON Always representating the data in the form of Key-Value Pairs. * JSON Data always key must be an "String" format and value can be any format i.e.,string,number,boolean,Date. * JSON Data is an lightweight when compared with XML Data. * The Process of Converting from Java Object into JSON Object called "Serialization" The Process of Converting Back from JSON Object into Java Object called "Deserialization". * To Perform the Serialization & De-Serialization process following are libaries area available Jackson,GSON etc., Example ======= Employee emp = new Employee(); emp.setEmpId(123); emp.setEmpName("Mahesh"); emp.setEmpDesignation("Software Engineer"); JSON ==== { "empId" : 123, "empName":"Mahesh", "empDesignation":"Software Engineer" } { "employee" : { "empId" : 123, "empName":"Mahesh", "empDesignation":"Software Engineer" } } Employee.java ============== package com.ashokit.model; import java.util.Date; import java.util.List; import com.ashokit.custom.CustomDateSerialzer; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonRootName("employee") @JsonInclude(value = Include.NON_NULL)//include only non-null values public class Employee { @JsonProperty(value = "employee_id")//changing property name for serialization private int id; @JsonProperty(value = "employee_name") private String name; @JsonProperty(value = "employee_designation") private String designation; @JsonProperty(value = "employee_dob") @JsonSerialize(using = CustomDateSerialzer.class) private Date dob; private boolean workFromHome; private List
address; private JobDetails jobDetails; 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 getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public boolean isWorkFromHome() { return workFromHome; } public void setWorkFromHome(boolean workFromHome) { this.workFromHome = workFromHome; } public void setAddress(List
address) { this.address = address; } public List
getAddress() { return address; } public void setJobDetails(JobDetails jobDetails) { this.jobDetails = jobDetails; } public JobDetails getJobDetails() { return jobDetails; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + ", dob=" + dob + ", workFromHome=" + workFromHome + ", address=" + address + ", jobDetails=" + jobDetails + "]"; } } Address.java ============ package com.ashokit.model; public class Address { private int addressId; private String addressType; private String doorNo; private String street; private String city; private JobDetails jobDetails; public int getAddressId() { return addressId; } public void setAddressId(int addressId) { this.addressId = addressId; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public String getDoorNo() { return doorNo; } public void setDoorNo(String doorNo) { this.doorNo = doorNo; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public void setJobDetails(JobDetails jobDetails) { this.jobDetails = jobDetails; } public JobDetails getJobDetails() { return jobDetails; } @Override public String toString() { return "Address [addressId=" + addressId + ", addressType=" + addressType + ", doorNo=" + doorNo + ", street=" + street + ", city=" + city + ", jobDetails=" + jobDetails + "]"; } } JobDetails.java =============== package com.ashokit.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(value = Include.NON_NULL) public class JobDetails { private String jobId; private String jobBand; public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getJobBand() { return jobBand; } public void setJobBand(String jobBand) { this.jobBand = jobBand; } @Override public String toString() { return "JobDetails [jobId=" + jobId + ", jobBand=" + jobBand + "]"; } } CustomDateSerialzer.java ======================== package com.ashokit.custom; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class CustomDateSerialzer extends StdSerializer { public CustomDateSerialzer() { this(null); } protected CustomDateSerialzer(Class t) { super(t); // TODO Auto-generated constructor stub } @Override public void serialize(Date dateValue, JsonGenerator gen, SerializerProvider provider) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); gen.writeString(sdf.format(dateValue)); ;} } JSONClient.java =============== package com.ashokit.client; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.ashokit.model.Address; import com.ashokit.model.Employee; import com.ashokit.model.JobDetails; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; public class JsonClient { public static void main(String[] args) throws IOException { //Employee object Employee emp = new Employee(); emp.setId(1122); emp.setName("Mahesh"); emp.setDesignation("Software Engineer"); emp.setDob(new java.util.Date()); emp.setWorkFromHome(true); JobDetails jd = new JobDetails(); jd.setJobId("3434"); jd.setJobBand("A3"); JobDetails jd1 = new JobDetails(); jd1.setJobId("4567"); jd1.setJobBand("A1"); List
addresses = new ArrayList
(); //Address object Address add = new Address(); add.setAddressId(123); add.setAddressType("Permanent"); add.setDoorNo("1-2-3"); add.setStreet("XYZ"); add.setCity("Hyderabad"); add.setJobDetails(jd); Address add1 = new Address(); add1.setAddressId(123); add1.setAddressType("Temporary"); add1.setDoorNo("11-22-33"); add1.setStreet("ABC"); add1.setCity("Bangalore"); add1.setJobDetails(jd1); addresses.add(add); addresses.add(add1); //setting the address emp.setAddress(addresses); //Creating the object for ObjectMapper class ObjectMapper mapper = new ObjectMapper(); //JSON Root Element Configuration mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); //performing the serialization String jsonData = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp); System.out.println(jsonData); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); writer.writeValue(new File("employee.json"), emp); System.out.println("Completed Creating File"); } } OUTPUT ======= { "employee" : { "workFromHome" : true, "address" : [ { "addressId" : 123, "addressType" : "Permanent", "doorNo" : "1-2-3", "street" : "XYZ", "city" : "Hyderabad", "jobDetails" : { "jobId" : "3434", "jobBand" : "A3" } }, { "addressId" : 123, "addressType" : "Temporary", "doorNo" : "11-22-33", "street" : "ABC", "city" : "Bangalore", "jobDetails" : { "jobId" : "4567", "jobBand" : "A1" } } ], "employee_id" : 1122, "employee_name" : "Mahesh", "employee_designation" : "Software Engineer", "employee_dob" : "06-03-2023 07:35:34" } } Completed Creating File JsonDeSerializerClient.java =========================== package com.ashokit.client; import java.io.File; import java.io.IOException; import com.ashokit.model.Employee; import com.fasterxml.jackson.core.exc.StreamReadException; import com.fasterxml.jackson.databind.DatabindException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonDeSerializerClient { public static void main(String[] args) throws StreamReadException, DatabindException, IOException { ObjectMapper mapper = new ObjectMapper(); //Enable Feature for Deserialize the Root element mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); Employee emp = mapper.readValue(new File("employee.json"),Employee.class); System.out.println(emp); } } OUTPUT ------ Employee [id=1, name=Ashok, desgination=SoftwareEngineer, salary=35000.0, createdDate=Sat Dec 21 07:09:44 IST 2024, jobDetails=JobDetails [jobId=JD123, jobBand=A3], address=[Address [doorNo=1-2-3, cityName=Hyderabad, state=Telegana, type=Permanent], Address [doorNo=3-2-1, cityName=Hyderabad, state=Telegana, type=Present]]] Introduction To Spring Boot Rest ================================ * Rest API Development = 1) Producer Development(API) 2) Consumer Development(Java Application,Dotnet App,PHP App,Python App etc..,)' * As you know already about Spring MVC(Configuration) >>>>>>> Spring Boot MVC (No Configuration) Spring Rest(Configuration) >>>>>>> Spring Boot Rest(No Configuration) * Offically we don't have any module related to Spring Rest or Spring Boot Rest because Rest API development is an extension of Spring MVC (or) Spring Boot MVC Development. Spring Rest/Spring Boot Rest = Spring MVC ++ / Spring Boot MVC++ * Inorder to develop the WebApplications (or) Distributed Application in Spring Boot, we are going to use same starter in Spring Boot i.e.,"Spring-boot-Starter-web". * In WebApplication Development we developed Several Controller Classses i.e,EmployeeController,LoginController, RegistrationController etc.,and these classes are annotated with @Controller Stero type Annotation In DistributedApplication Development we need to develop RestController Classes using specialized annotation of @Controller i.e., @RestController Spring MVC/Spring Boot MVC = @Controller + @ResponseBody @Controller public Class EmployeeController{ @PostMapping(value="/registration") @ResponseBody public String processRegistration(){ } @GetMapping(value="/passwordLink") @ResponseBody public String processPasswordLink(){ } } * The Problem of developing Rest API's using SPring MVC as programmer we need to add the dependencies related to JACKSON API & JAX-B API in pom.xml file. * Every RequestHandler Method Should need to add the extra annotation i.e.,@ResponseBody to deliver the Response to Client. * To Overcome the above Problem we need to develop the controller in Rest API's using annotation @RestController which is an Combination of two Annotations i.e., @Controller + @ResponseBody @RestController = @Controller + @ResponseBody Example ======= @RestController public Class EmployeeController{ @PostMapping(value="/registration") public String processRegistration(){ } @GetMapping(value="/passwordLink") public String processPasswordLink(){ } } * In Spring MVC/Spring Boot MVC flow contains the ViewResolver for Rendering view Components i.e.,(Html,JSP,Thymeleaf etc.,) In Spring Rest/Spring Boot Rest flow doesn't contains the ViewResolver for delivering the Response in global formats (XML,JSON) to Various Clients. Example ======= Browser >>>>>>>>>>> www.ashokittech.com >>>>>>>>>>>>>>> RazorPay (Payment Related Processing) (WebApplication) (Distributed Application) (@Controller) (@RestController)' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++