JSON序列化 - 删除空键序列化、JSON

由网友(衬他孤独)分享简介:我创建使用.net的Web API技术HTTP服务,我已经创造了一些DTO类和时只需要数据的某个子集,我打算只填充的DTO该数据的最小化量传输的数据。有没有办法得到的JSON串行器忽视这些数据成员是空的?我知道还有的[JsonIgnore]和[ScriptIgnore]属性,它们会忽略特定的成员,但我只想要忽略他们,如...

我创建使用.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});
 

C JSON的序列化和反序列化

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 });

阅读全文

相关推荐

最新文章