如何将jackson json null字符串序列化为空字符串 [英] How to serialize in jackson json null string to empty string
问题描述
我需要jackson json(1.8)将java NULL字符串序列化为空字符串。你怎么做呢?
非常感谢任何帮助或建议。
I need jackson json (1.8) to serialize a java NULL string to an empty string. How do you do it? Any help or suggestion is greatly appreciated.
谢谢
推荐答案
请参阅自定义序列化程序的文档;有一个这样的例子,适合我。
See the docs on Custom Serializers; there's an example of exactly this, works for me.
如果文档移动,请让我粘贴相关答案:
In case the docs move let me paste the relevant answer:
将空值转换为其他值
(如空字符串)
如果你想要输出一些其他JSON值而不是null(主要是
,因为其他一些处理工具更喜欢其他常量值 -
经常是空字符串),事情有点棘手,因为名义类型可能是
任何东西;虽然您可以为 Object.class
注册序列化程序,但除非没有更多特定的序列化程序可供使用,否则不会使用
。
If you want to output some other JSON value instead of null (mainly
because some other processing tools prefer other constant values --
often empty String), things are bit trickier as nominal type may be
anything; and while you could register serializer for Object.class
, it
would not be used unless there wasn't more specific serializer to use.
但是有一个特定的null serializer概念,您可以使用
如下:
But there is specific concept of "null serializer" that you can use as follows:
// Configuration of ObjectMapper:
{
// First: need a custom serializer provider
StdSerializerProvider sp = new StdSerializerProvider();
sp.setNullValueSerializer(new NullSerializer());
// And then configure mapper to use it
ObjectMapper m = new ObjectMapper();
m.setSerializerProvider(sp);
}
// serialization as done using regular ObjectMapper.writeValue()
// and NullSerializer can be something as simple as:
public class NullSerializer extends JsonSerializer<Object>
{
public void serialize(Object value, JsonGenerator jgen,
SerializerProvider provider)
throws IOException, JsonProcessingException
{
// any JSON value you want...
jgen.writeString("");
}
}
这篇关于如何将jackson json null字符串序列化为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!