Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

Sunday, March 3, 2024

Top 27 Gson Interview Questions with Answers for Java Developers

Hello guys, parsing and creating JSON is a very common task in any Java application, particularly spring based application and that's why its important for a Java developer to not just understand the JSON format but also to be familiar with the important JSON parsing libraries in Java like Gson and Jackson. It's not just important for your day to day Java development work but also for interviews as there is a increased focus on checking if candidate is familiar with key JSON libraries like Jackson or Gson or not. Since I shared Java interview questions on core Java topics like concurrency, abstract class, static, and final modifier, a lot of my reader asked me to share JSON related interview questions as well. 

So I thought about this article and here I am going to share all the JSON related questions which I have seen on interviews as well as I expect from a candidate. This not just include checking your ability to read and write JSON but also your knowledge about Gson and Jackson, two popular JSON libraries in Java. 


27 JSON Gson Interview Questions with Answers 

Without any further ado, here is a list of 20 JSON interview questions and answers, you can review these questions to not just refresh your knowledge about JSON parsing in Java but also prepare for interviews. 


1. What is the use of GSON?
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. It's one of the popular JSON parsing library we have in Java and its created by none other than Google who have also created Google Protocol Buffer, also known as protobuf. 

20 JSON Gson Interview Questions with Answers




2. Is GSON thread safe?
Gson is not thread-safe. It doesn't provide any built-in thread safety mechanism but you can make your code thread-safe by following concurrency best practices like using local variables, Immutable objects, using ThreadLocal variables, and synchronizing access. 

There is also this sentence in the docs: The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.The core Gson class is thread-safe.


3. What is Jackson?
Jackson is a very popular and efficient Java-based library to serialize or map Java objects to JSON and vice versa. You can also see my previous articles 3 ways to parse JSON in Java to learn more about Jackson libraries. 

how to parse json in Java




4. How to convert a Java object to JSON String using Gson?
By using Gson.toJson() method.

5. How to convert a JSON String to Java object?
By using Gson.fromJson() method, if you need code, you can also see this example of parsing JSON using Gson in Java


6. Can you use the same Gson object to convert more than one Java object to JSON?
Since, the Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.

7, How to use Gson with Maven?
Just use the following Maven dependency


8. How to use Gson without using Maven?
If you are not using Maven then you should download the Gson.jar file from Maven central library and include this into your application's classpath.


9. How to use Gson with Gradle?
Just add following dependency:

compile 'com.google.code.gson:gson:2.8.0'

10. Does fields from super class is included during JSON serialization by Gson?
Yes, All fields in the current class (and from all super classes) are included by default.


11. How to exclude a filed from JSON Serialization?
Similar to Java Serialization, you can use the transient keyword to exclude a field from Java class while converting into jSON String. If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization by Gson.


12. What will happen if a field is null on Java object? What will be the value in JSON String?
While serializing, a null field is skipped from the output by Gson.


13. Does Gson mandate that the Java model classes need a constructor/getter/setter?
No, Gson doesn't impose any restriction like that. Your Java model class may or may not contain constructor.


14. Can the Java model files be private?
Not, it must be public so that it can be accessed by libraries which are outside the package. 


15. How does null values are handled by Gson?
In Gson, null values are handled in a specific way during serialization and deserialization. When Gson serializes a Java object to JSON, it omits fields with null values by default. This behavior is intended to reduce the size of the resulting JSON and is aligned with the idea that null values may not be necessary or meaningful in the context of the JSON representation.

import com.google.gson.Gson;

public class Example {
    public String name;
    public Integer age;

    public static void main(String[] args) {
        Example example = new Example();
        example.name = "John";
        // age is not assigned, so it is null

        Gson gson = new Gson();
        String json = gson.toJson(example);

        System.out.println(json);
    }
}

The resulting JSON will only include the "name" field:

{"name":"John"}

During deserialization, Gson sets fields with missing or null values in the JSON to their default values. If a field is entirely absent from the JSON, it is initialized to its default value (null for objects, 0 for numeric types, false for boolean, etc.).

Here's an example:

import com.google.gson.Gson;

public class Example {
    public String name;
    public Integer age;

    public static void main(String[] args) {
        String json = "{\"name\":\"John\"}";

        Gson gson = new Gson();
        Example example = gson.fromJson(json, Example.class);

        System.out.println("Name: " + example.name); // John
        System.out.println("Age: " + example.age);   // null (default value for Integer)
    }
}

In this case, the "age" field is set to its default value (null) because it is not present in the JSON.

It's important for Java developers to be aware of Gson's default behavior regarding null values, as it may impact the way you design your Java classes and handle JSON data in your application.


16, What happens if the Java class has different field naming than the JSON during de-serialization?
When the field names in a Java class do not match the names in the JSON during deserialization using Gson, the library provides mechanisms to handle this discrepancy. Gson offers flexibility through annotations and custom strategies to map JSON field names to corresponding Java class fields.

One common approach is to use the @SerializedName annotation provided by Gson. By annotating the Java class fields with @SerializedName and specifying the corresponding JSON field names, Gson can correctly map the JSON data to the appropriate Java fields, even if their names differ. 

For example:

import com.google.gson.annotations.SerializedName;

public class Example {
    @SerializedName("fullName")
    public String name;

    @SerializedName("years")
    public Integer age;
}

In this example, the @SerializedName annotation allows Gson to correctly map the "fullName" field in JSON to the "name" field in the Java class and the "years" field to the "age" field.

Alternatively, you can customize the field name mapping strategy globally by providing a custom FieldNamingStrategy to the Gson builder. This strategy allows you to define your own rules for transforming JSON field names to Java field names during deserialization.

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Field;

public class CustomNamingExample {
    public String fullName;
    public Integer years;

    public static void main(String[] args) {
        String json = "{\"fullName\":\"John Doe\",\"years\":25}";

        Gson gson = new GsonBuilder()
                .setFieldNamingStrategy(new CustomFieldNamingStrategy())
                .create();

        CustomNamingExample example = gson.fromJson(json, CustomNamingExample.class);

        System.out.println("Name: " + example.fullName); // John Doe
        System.out.println("Age: " + example.years);    // 25
    }

    static class CustomFieldNamingStrategy implements FieldNamingStrategy {
        @Override
        public String translateName(Field field) {
            if (field.getName().equals("fullName")) {
                return "name";
            } else if (field.getName().equals("years")) {
                return "age";
            }
            return field.getName();
        }
    }
}

In this custom naming strategy example, the field names are explicitly mapped during deserialization, providing granular control over the translation process.

Ultimately, Gson's flexibility in handling field name mismatches allows developers to adapt their Java classes to various JSON formats, promoting interoperability and ease of integration.


17. Can Gson serialize Inner class in Java?
Gson can deserialize nested static classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it


18. How to pretty print using Gson?
The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output.

 As well, "null" fields will be ignored in the output. If you would like to use the Pretty Print feature, you must configure your Gson instance using the GsonBuilder.

The following is an example shows how to configure a Gson instance to use the default JsonPrintFormatter instead of the JsonCompactFormatter
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);


19. Which fields are by default ignored by GSon?
Both transient and static fields are by default ignored by Gson during Serialization and Deserialization, but you can configure to exclude only transient or static as shown below:
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.create();
Now, this will only exclude static variables, hence transient variables will be included.


20. How to exclude volatile variable during JSON serialization/deserialization?
Similar to previous example, you can use the method excludeFieldsWithModifiers() to provide modifiers which can be excluded by Gson. For example, to exclude transient, static, and volatile fields, you can use following snippet:

Gson gson = new GsonBuilder()
   .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
.create();


21. Difference between Gson and org.json library in Java?
org.json is a much lower-level library that can be used to write a toJson() method in a class. If you can not use Gson directly (may be because of platform restrictions regarding reflection), you could use org.json to hand-code a toJson method in each object.


22. Difference between Gson and json-simple library?
org.json.simple library is very similar to org.json library and hence fairly low level. The key issue with this library is that it does not handle exceptions very well. In some cases it appeared to just eat the exception while in other cases it throws an "Error" rather than an exception


23. How to serialize/deserialize nested objects using Gson?
Serializing and deserializing nested objects using Gson involves specifying the appropriate type information and ensuring that the structure of your Java classes aligns with the structure of the nested JSON objects. You can also see my article how to serialize object using Gson for full code example


24. How to serialize/deserialize arrays/lists of objects using Gson?
Serializing and deserializing arrays or lists of objects using Gson is straightforward. Gson automatically handles these scenarios, and you only need to ensure that your Java classes and data structures align with the JSON structure. Here is an example of how to serialize array of object using Gson in Java. 


25. What happens if a field is not available in JSON while deserializing?
While deserializing, a missing entry in JSON results in setting the corresponding field in the object to null.


26. Does Gson keep a defined default value for a class property while executing .fromJson() and there isn't any value for that property available in JSON?
Yes, when Gson encounters a property in a Java class during deserialization (using .fromJson()) for which there is no corresponding value in the JSON data, it assigns the default value for that property based on its data type.

Here's a brief explanation of how Gson handles missing values during deserialization:

Primitive Types:
For primitive data types (int, double, boolean, etc.), Gson uses the default values if no corresponding value is present in the JSON. For example, an int property with no corresponding value in the JSON would be assigned the default value of 0.

Object Types (including Strings):
For non-primitive types (Objects, Strings, custom classes), Gson assigns null as the default value if no value is found in the JSON.


27. Does fields from Outer class is included when you convert Inner class object to JSON?
Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization.


28. What is difference between Gson and Jackson?
Gson and Jackson, both widely used Java libraries for JSON processing, exhibit differences in terms of design philosophy, features, and use cases. Developed by Google, Gson focuses on simplicity and ease of integration, providing a straightforward API for basic JSON processing tasks such as object-to-JSON and JSON-to-object conversion. 

On the other hand, Jackson, known for its comprehensive design, offers a more extensive set of functionalities, including streaming, data binding, and a tree model. Jackson's feature richness makes it suitable for various use cases, particularly those requiring advanced JSON processing capabilities.

In terms of performance, Gson is often considered simpler and lighter, leading to faster startup times for smaller to medium-sized applications. Jackson, with its high-performance streaming and data binding capabilities, is more suitable for larger-scale applications where complex JSON processing is involved.

Both libraries provide customization options, but they differ in their approaches. Gson offers annotations like @SerializedName and allows the registration of custom serializers and deserializers. Jackson, on the other hand, provides a rich set of annotations and a powerful ObjectMapper configuration for fine-grained control over serialization and deserialization processes.

When it comes to usage, Gson is commonly chosen for its simplicity and user-friendly API, making it suitable for smaller projects or scenarios where a lightweight JSON library suffices. In contrast, Jackson is preferred in more complex scenarios or enterprise-level applications where advanced features, high performance, and customization options are crucial. The choice between Gson and Jackson ultimately depends on the specific needs and complexity of the project at hand.

Here is also a nice table highlighting difference between Gson and Jackson:

20 JSON Gson Interview Questions with Answers



That's all about Gson interview questions for Java developer. I have mostly focused on  using Google's Gson library for converting Java object to/from JSON String, but most of the concepts are also valid for Jackson library. If you have any particular interview questions which you want to ask, feel free to ask in comments. 


2 comments :

Anonymous said...

When are we supposed to use Gson instead of Jackson API?

Anonymous said...

Thank god you are writing like before, I love when you write about interview questions and about Java

Post a Comment