我需要 jackson json (1.8) 将 java NULL 字符串序列化为空字符串。你怎么做呢?
非常感谢任何帮助或建议。
谢谢
最佳答案
见 docs on Custom Serializers ;有一个确切的例子,对我有用。
如果文档移动,让我粘贴相关答案:
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 - 如何在jackson json中将空字符串序列化为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5782284/