使用Flexjson时如何排除空值字段?
我正在使用 Flexjson 将这样的类序列化为 JSON:
public class Item {
private Long id;
private String name;
private String description;
...
// Getters and setters
...
}
许多 Item 字段可以为 null(例如,描述)。因此,当使用 Flexjson 序列化此类 Item 对象时,我会得到以下 JSON:
{"id":62,"name":"Item A","description":null,...}
正如我已经提到的,由于 Item 对象可能包含许多空值字段,因此输出的 JSON 比实际需要的长度要长。到目前为止,这是一个问题,因为我想通过 WiFi、3G、EDGE 或 GPRS 通过无线连接将生成的 JSON 从 Web 服务器发送到移动客户端(即需要更多带宽,这会导致速度降低) )。
因此,我想问如何使用 Flexjson (有效)排除空值属性?
谢谢!
I am serializing a class like this into JSON using Flexjson:
public class Item {
private Long id;
private String name;
private String description;
...
// Getters and setters
...
}
Many of the Item fields can be null (e.g., description). Consequently, when such an Item object is serialized using Flexjson, I get the following JSON:
{"id":62,"name":"Item A","description":null,...}
Since, as I already mentioned, an Item object may contain many null-value fields, the outcoming JSON is longer than effectively needed. This is in so far a problem, because I would like to send the generated JSON from a web server to a mobile client over a wireless connection via WiFi, 3G, EDGE or GPRS (i.e., more bandwidth is required, which results in less speed).
Therefore, I wanted to ask how it is possible to (efficiently) exclude null-value attributes using Flexjson?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用以下转换器:
具有以下用法:
请注意,所有空字段都将被排除。
不支持按路径(相对于类)添加转换器,因为 FlexJSON 强制 TypeTransformer 为空值:
JSONContext.java:第 95 行:
You can use the following transformer :
with the following usage :
Note that all null fields will be excluded.
Adding the Transformer by Path (vs by Class) is not supported as FlexJSON forces TypeTransformer for null values :
JSONContext.java : line 95 :
我是一个新手,我遇到了同样的问题,在 Source Forge 上找不到任何解决方案,所以我使用正则表达式从 JSON 字符串中删除所有空值
I am a newbie,i had same problem and could not find any solution on source forge so i used regular expression to remove all the nulls from JSON String
我还没有确切地尝试过您的情况,但我相信以下内容应该可以解决您的问题:
显然,您可能会使用 getter 访问描述字段。此外,您可能希望使用反射来迭代实例字段以排除空字段。
I haven't tried out your situation exactly, but I believe the following should solve your problem:
Clearly, you'd probably access the description field using a getter. Additionally, you might want to iterate your instance fields using reflection to exclude the null-fields.