Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Gson and Jackson annotations coexist in the same POJO?

I'm working on a legacy Android project which uses a very old version of Jackson lib to parse JSONs brought from our web API.

I am currently working on a new feature for said project, and would like to use Retrofit with Gson lib as its JSON parser, since both libs provide more flexibility and a cleaner code if compared to our previous lib choices.

Problem is, I will need some of the legacy POJOs, and those already have Jackson annotations. Does putting Gson and Jackson annotations in the same class generate any conflicts? Or will I be forced to create mirror classes with Gson annotations in order to avoid potential issues?

Example:

import org.codehaus.jackson.annotate.JsonProperty;
import com.google.gson.annotations.SerializedName;

public class someClass {

    @JsonProperty ("some_attribute") // Jackson annotation
    @SerializedName("some_attribute") // Gson annotation
    private String someAttribute;

}
like image 928
junit-1988 Avatar asked Oct 05 '15 21:10

junit-1988


People also ask

What is the difference between GSON and Jackson?

Conclusion Both Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.

Is GSON faster than Jackson?

Last benchmarks Jackson was the winner, but this time GSON is by far the fastest, with JSONP being a close second and then followed by Jackson and then JSON.

Does GSON use JsonProperty?

No, there is not. As I recall, there is a post in the mailing list from a core developer that Gson won't likely be so enhanced, either.


1 Answers

Annotations are just metadata. They don't have any behavior on their own.

What does have behavior is the corresponding component that processes the annotation. For example, Jackson's ObjectMapper (its internals) reads the type you provide, introspects it to find any meaningful annotations, and uses them to serialize/deserialize. @SerializedName isn't meaningful to Jackson, so it ignores it. Similarly, @JsonProperty isn't meaningful to Gson, so it ignores it.

There won't be any issues*.

* Unless you write your own type adapters that for whatever reason use another library's annotations.

like image 56
Sotirios Delimanolis Avatar answered Sep 28 '22 05:09

Sotirios Delimanolis