I am developing a Java library that can be used to call a certain web API that is using JSON data format to pass information. Said library will only contain data classes according to the data structure defined by the API spec. Code required to call the API will be placed in a second library.
In Java enterprise applications, there are several JSON parsing libraries available, like JSON-B or Jackson. I want to design my library to be somewhat agnostic of the underlying JSON implementation.
Let's assume my library has a class Article:
public class Article {
String id;
String headline;
String content;
}
To make that class suitable for use in JSON-B-enabled applications, I would have to provide the following annotations with my class, along with a project dependency to e.g. jakarta.json.bind:jakarta.json.bind-api:
public class Article {
@JsonbProperty("id")
String id;
@JsonbProperty("headline")
String headline;
@JsonbProperty("content")
String content;
}
To make that class suitable for use in Jackson-enabled applications, I would have to provide the following annotations with my class, along with a project dependency to e.g. com.fasterxml.jackson.core:jackson-annotations:
public class Article {
@JsonProperty("id")
String id;
@JsonProperty("headline")
String headline;
@JsonProperty("content")
String content;
}
I have seen libraries for Quarkus offering distinct versions for both frameworks, like quarkus-resteasy-reactive-jsonb and quarkus-resteasy-reactive-jackson, but those do not have POJO classes to serialize. I could provide three modules of my library, a base version and versions for JSON-B and Jackson, but I can't wrap my head around how to do it without duplicating / extending lots of classes and dependencies.
The idea is that for each of the individual JSON library modules , you have to develop some generic codes that can serialise/deserialise between a given POJO and JSON by using that JSON library 's API.
The annotation approach provided by the JSON library is just a high level way for processing the JSON. There should be the some way to do the same thing without POJO and annotations and you should check each of the JSON library for how to do that when developing those generic codes. For example in Jackson, you can represent the JSON structure as a map instead of POJO
To keep the POJO to be agnostic of any JSON libraries , you can also consider to define your own annotations for annotating the POJO. Those generic codes in each JSON modules can then make use of it to make the decision.