如何在jackson json中将空字符串序列化为空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5782284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serialize in Hymanson json null string to empty string
提问by jun
I need Hymanson 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.
我需要 Hymanson json (1.8) 将 java NULL 字符串序列化为空字符串。你怎么做呢?非常感谢任何帮助或建议。
Thanks
谢谢
回答by enigment
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:
如果文档移动,让我粘贴相关答案:
Converting null values to something else
(like empty Strings)
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.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(""); } }
将空值转换为其他值
(如空字符串)
如果你想输出一些其他的 JSON 值而不是 null(主要是因为其他一些处理工具更喜欢其他的常量值——通常是空字符串),事情有点棘手,因为名义类型可能是任何东西;虽然您可以为 注册序列化程序
Object.class,但除非没有更具体的序列化程序可供使用,否则不会使用它。但是您可以使用“空序列化器”的特定概念,如下所示:
// 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(""); } }

