json - 如何在jackson json中将空字符串序列化为空字符串

标签 json jackson

我需要 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/

相关文章:

javascript - 使用 api 检查文件是否在 Chrome 中下载

java - 当 Object 变量设置为 Private 时,Jackson ObjectMapper 返回 null

java - JSON 序列化时 jsonrpc4j null

mysql - 有没有更好的方法来编码 sql 行?

python - 在mysql数据库的单个单元格中插入python字典

java - 创建java函数来重复添加对象

java - 使用 TypeReference 的具有泛型类型的 JSON 反序列化器

java - spring cache redis : LazyInitializationException failed to lazily initialize a collection, 无法初始化代理 - 无 session

C# Json.Deserialize with Object with Child class with interfaces

javascript - 使用 Javascript 的多个日期时间之间的平均天数