如何通过自定义 JsonSerializer 传递上下文?(Java,ObjectMapper)

我有自定义的 JsonSerializer:


new JsonSerializer<T>() {

    @Override

    public void serialize(T instance, JsonGenerator gen, SerializerProvider sp) throws IOException, JsonProcessingException

    {

        try {

            instance = someFunction(instance);

            SerializableString serializableString = new SerializedString(defaultMapper.writeValueAsString(instance));

            gen.writeRawValue(serializableString);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

对于我的 Pourpuses,我需要一种方法来传递gen.getOutputContext()到defaultMapper.writeValueAsString(instance). 有没有办法实现这一目标?或者我是否以错误的方式使用 ObjectMapper?感谢您的任何见解。


编辑:defaultMapper是类型ObjectMapper。


Helenr
浏览 309回答 2
2回答

ABOUTYOU

该ObjectMapper居然有正是我需要建在方法- ObjectMapper.writeValue(JsonGenerator, T)。来自我的问题的修改(和功能)代码:new JsonSerializer<T>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void serialize(T instance, JsonGenerator gen, SerializerProvider sp) throws IOException, JsonProcessingException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; instance = someFunction(instance);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defaultMapper.writeValue(gen, instance)&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java