简体   繁体   中英

How to implement JSON functionality in a shared library without hard-wiring third party dependencies

I'm writing a class to provide some logging output in JSON format.

One issue is that the various Java projects I work on already use JSON and have dependencies on 3rd party libraries like gson or Jackson.

The work the class needs to perform is quite small and I figured it should be easy to avoid creating a new dependency on any particular JSON library, analagous to SLF4j which picks up whatever logging framework is already present.

My plan is that the class would pick up a JSON engine and use it, or throw a "missing JSON library" exception at start-up.

Does this already exists? I can't find anything on the net.

Is the Java JDK service provider java.util.ServiceLoader suitable?

It seemed easy enough to implement when I used it to plug in a java.nio.file.spi.FileTypeDetector for mime type detection with Apache Tika (best explained on this useful blog post .

You could try Class.forName(), passing the full name of the core class for Gson, Jackson, or whatever other JSON library is in use. If the class is not on the classpath, you will get a ClassNotFound exception. If you did this test only once, the cost would be reasonable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM