Tuesday, 8 October 2019

Convert Java Object to Json String using GSON

JSON Stand for JavaScript Object Notation. It’s a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and a web application.

Below given APIs can be used to convert a Java object into JSON:
1. GSON: It is an open-source Java library which is used to serialize and deserialize Java objects to JSON.
2. Jackson API

Employee.java Pojo class
package com.algorithmforum.gson;
public class Employee {
            private int age;
            private String name;
            private String gender;
            public Employee(int age, String name, String gender) {
                        this.age = age;
                        this.name = name;
                        this.gender = gender;
            }
            // Setters and Getters
}

Default Serialization using Gson
See the code below for the default serialization using Gson Library.

package com.algorithmforum.gson;
import com.google.gson.Gson;
public class ParseToJsonUsingGsonTest {
            public static void main(String[] args) {
                        Employee employee = new Employee(10, "Awadh", "F");
                       
                        Gson gson = new Gson();
                        String empStr = gson.toJson(employee);
                        System.out.println(empStr);
            }
}
Output:
{"age":10,"name":"Awadh","gender":"F"}

Custom Serialization using Gson
We can change the default serialization by registering Type adapter for the Particular Pojo (for which serialization behavior needs to be changed). See the code below.

package com.algorithmforum.gson;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class ParseToJsonUsingCustomGsonTest {

            public static void main(String[] args) {
                        Employee employee = new Employee(10, "Awadh", "M");

                        Gson gson = new GsonBuilder().registerTypeAdapter(Employee.class, new EmployeeSeriliazer()).create();
                        String empStr = gson.toJson(employee);
                        System.out.println(empStr);
            }
}

class EmployeeSeriliazer implements JsonSerializer {

            @Override
            public JsonElement serialize(Employee src, Type typeOfSrc, JsonSerializationContext context) {
                        JsonObject jsonMerchant = new Gson().toJsonTree(src).getAsJsonObject();
                        String gender = src.getGender();
                        String salutation = null;
                        if (gender != null) {
                                    salutation = gender.equals("M") ? "Mr. " : "Ms. ";
                        }
                        jsonMerchant.addProperty("name", salutation + src.getName());
                        return jsonMerchant;
            }
}

Output:
{"age":10,"name":"Mr. Awadh","gender":"M"}

In the above custom serializer, we are adding salutation with the name on the basis of gender.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...