我如何正确地重用Jackson ObjectMapper? [英] How do I correctly reuse Jackson ObjectMapper?
问题描述
我对我的应用程序中ObjectMapper的工作方式和常规使用感到满意.我想了解的是实现ObjectMapper的最佳方法,以确保可重复使用它,并且我不会在应用程序内创建不必要的实例?
I am happy with how the ObjectMapper works and general use within my application. What I would like to understand is the best way to implement the ObjectMapper to ensure it is re-used and I'm not creating unnecessary instances within my application?
我的想法是可以在Utils类中声明ObjectMapper,如下所示:
My thoughts are that I can declare the ObjectMapper in a Utils class as follows:
public class Utils {
public final static ObjectMapper mapper = new ObjectMapper();
}
然后,我可以使用各种代码从需要的各个地方引用它,例如:
I could then reference this from the various places I need to using code such as:
JsonSimple jsonSimple = Utils.mapper.readValue(jsonString, JsonSimple.class);
我遇到了另一个问题(我应该将Jackson的ObjectMapper声明为静态字段?)提示了我的方法.我认为可能的主要区别在于,我想跨许多不同的类共享我的ObjectMapper实例,而不仅仅是在一个类中共享.
I came across this other question (Should I declare Jackson's ObjectMapper as a static field?) that prompted my approach. I think maybe the key difference is that I want to share my ObjectMapper instance across many different classes, not just within a single class.
这种方法听起来合适还是我遗漏了一些东西?
Does this approach sound appropriate or am I missing something?
谢谢
推荐答案
每个应用程序可以使用一个实例,前提是您必须在可见后不调用任何配置方法,即您应该在静态内部进行所有初始化阻止.
It's fine to use a single instance per application provided you don't call any configuration methods after it's been made visible i.e. you should do all your initialization inside a static block.
这篇关于我如何正确地重用Jackson ObjectMapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!