如何使用杰克逊将布尔值以字符串形式序列化为JSON到JSON [英] How to serialize boolean to JSON as strings using Jackson

查看:123
本文介绍了如何使用杰克逊将布尔值以字符串形式序列化为JSON到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经使用Jersey JAX-RS和Jackson(2.1.5版)开发了REST服务以进行JSON序列化.

We have developed a REST service using Jersey JAX-RS and Jackson (version 2.1.5) for JSON serialization.

由于该应用程序将替代旧的旧服务(充当现有移动应用程序的后端)的替代品,因此我们需要对Jackson序列化布尔值的方式进行一些调整.

As the application is supposed to be a drop-in replacement for the older legacy service acting as a backend to an existing mobile app, we need to do some tweaking to the way Jackson serializes boolean values.

现有的移动应用希望布尔值像这样用"true"和"false"的字符串表示:

Existing mobile app expects boolean values to be expressed as strings of "true" and "false" like this:

{"Foo":"true","Bar":"false"}

所以我一直在寻找一种方法来影响Jackson序列化以将布尔值输出为字符串,但是我没有成功.

So I have searched for a way to influence the Jackson serialization to output booleans as strings, but I have no success.

哦,顺便说一句-由于我们的模型类是使用JAXB类生成从xml模式生成的,因此我们无法使用json注释对这些类进行注释.

Oh, and btw - since our model classes have been generated from xml schemas using JAXB class generation, we can not annotate the classes with json annotations.

我试图在ObjectMapper中注册一个模块,该模块为布尔对象提供了自定义的序列化器,但似乎不起作用.

I have tried to register a module with ObjectMapper, that provides a customized serializer for boolean objects, but it did not seem to work.

推荐答案

好吧,看来我的IDE或Maven都在起作用,拒绝构建或引用我在ObjectMapper配置中所做的更改.

Okay, it seems that either my IDE or Maven was acting up and refused to build or reference the changes I made in my ObjectMapper configuration.

为了将来的访问者,这是解决使Jackson数据绑定以将布尔值作为字符串吐出的问题的解决方案:

For the sake of the future visitors, here is the gist of the solution to the issue of making Jackson data binding to spit out boolean values as strings:

在我自定义的ObjectMapper上下文解析器中,我只需要为布尔对象类型添加特殊的序列化器:

In my customized ObjectMapper context resolver, I just had to add special serializer for boolean object types:

// create a module with a custom Boolean serializer
SimpleModule module = new SimpleModule("BooleanAsString", new Version(1, 0, 0, null, null, null));
module.addSerializer(new NonTypedScalarSerializerBase<Boolean>(Boolean.class){
    @Override
    public void serialize(Boolean value, JsonGenerator jgen, SerializerProvider provider)
    throws IOException, JsonGenerationException {
        ObjectMapperProvider.log.debug("serializing boolean value as a Strng");
        jgen.writeString(value.toString());
    }
});
// Here's where we configure the object mapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

就是这样.如果您知道如何配置ObjectMapper,那么这足以使您开始工作.

That's it. If you know how to configure your ObjectMapper, then this should be enough to get you going.

这篇关于如何使用杰克逊将布尔值以字符串形式序列化为JSON到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆