gson:将null视为空字符串 [英] gson: Treat null as empty String

查看:1036
本文介绍了gson:将null视为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 google-gson 将Java地图序列化为JSON字符串。它提供构建器处理空值

I use google-gson to serialize a Java map into a JSON string. It provides a builder handles null values:

Gson gson = new GsonBuilder().serializeNulls().create();

问题是结果是字符串 null ,如下所示:

The problem is that the result is the string null, as in:

gson.toJson(categoriesMap));
{"111111111":null}

所需结果是:

{"111111111":""}

我可以为 null 做一个字符串替换,但这很丑并容易出错。是否有本地gson支持添加自定义字符串而不是 null

I can do a String-replace for null and "", but this is ugly and prone to errors. Is there a native gson support for adding a custom String instead of null?

推荐答案

如果这是您的应用程序类型,您可以注册一个类型适配器。但Gson不允许你改变字符串或原始类型的序列化形式。

If this were your application type, you could register a type adapter. But Gson doesn't allow you to change the serialized form of strings or primitive types.

最好的办法是改变你的Java对象。或者放宽对空位的限制。

Your best bet is to change your Java objects. Or to loosen the restriction around nulls.

这篇关于gson:将null视为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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