What is JSON ,POJO, Serialization and Deserialization - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Sunday, 19 April 2020

What is JSON ,POJO, Serialization and Deserialization

What is JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

So we use JSON to communicate between client and servers

 JSON is a text format that is completely language independent

Whenever the communication happens between client and server

For Example : if you want to create a new Employee

Employee emp=new Employee(1,"Neeraj", 32);

From Client To Server
Now client will send this as JSON Object to Server and then the server on which Java code is deployed , it knows how to convert JSON to Employee Object and create a new Employee.

From Server To Client
Now Server can't send Java Object To client , because client doesn't understand what is Java Object or .net Object or whatever programming language we use, so Server converts the Object into JSON so that client can understand .

So we can say JSON is universal language to communicate. because server can have application deployed from any Language like Java, Ruby, Php, so we send data to client in JSON so that it is easy to understand

We have libraries to Convert Object to JSON

This process of converting OBJ--> JSON is called (Marshelling)

POJO-->JSON (Marshelling)

JSON to OBJ is called Un-Marshelling

JSON-->POJO (Un-Marshelling)

Gson
Jackson
Simple JSON
JSON SOUP


Serialization is process of breaking the object(to be sent across network) into form that can be sent across the network (that is converting it into to a sequence of bytes).




Serialization – Write JSON using Gson

Gson toJson() Example

Employee emp = new Employee(999, "Neeraj", "Bakhtani", "testing@gmail.com");
     
Gson gson = new Gson();

String jsonString = gson.toJson(emp); // As in Serialization  we convert the Java Object to Json, so //we using function here toJson

System.out.println(jsonString);



Deserialization in the context of Gson means converting a JSON string to equivalent Java object.





Deserialization – Read JSON using Gson

Gson fromJson() Example
String jsonString = "{'id':999, 'firstName':'Neeraj', 'lastName':'Bakhtani', 'email':'testing@gmail.com'}";
     
Gson gson = new Gson();

Employee empObject = gson.fromJson(jsonString, Employee.class); // we want to Deserialize so we use function fromJson as we already have Json and want to convert into Java Object of Employee class

System.out.println(empObject);

No comments:

Post a Comment