JSON序列化 - 删除空键 [英] JSON Serialisation - removing empty keys

查看:134
本文介绍了JSON序列化 - 删除空键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用.net的Web API技术HTTP服务,我已经创造了一些DTO类和时只需要数据的某个子集,我打算只填充的DTO该数据的最小化量传输的数据。

有没有办法得到的JSON串行器忽视这些数据成员是空的?我知道还有的[JsonIgnore]和[ScriptIgnore]属性,它们会忽略特定的成员,但我只想要忽略他们,如果他们是null或空。

由于以下L.B

我增加了以下内容WebApiConfig.cs,使这个在网络API:

  VAR JSON = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
 

解决方案

Json.Net 具有这样的设置

  VAR海峡= JsonConvert.SerializeObject(OBJ,
    新JsonSerializerSettings(){NullValueHandling = NullValueHandling.Ignore});
 

I'm creating a HTTP service using the .Net Web API technology, I've created some DTO classes and when only a certain subset of data is needed I'm planning on only filling the DTOs with that data to minimise the amount of data transferred.

Is there any way of getting the JSON serialiser to ignore those data members that are empty? I realise there's the [JsonIgnore] and [ScriptIgnore] attributes which will ignore specific members, but I only want to ignore them if they are null or empty.

[Edit]

Thanks to L.B below

I added the following to WebApiConfig.cs to enable this in Web API:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

解决方案

Json.Net has a setting for this

var str = JsonConvert.SerializeObject(obj, 
    new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });

这篇关于JSON序列化 - 删除空键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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