如何删除JSON字符串中的空值 [英] How to remove null value in json string

查看:815
本文介绍了如何删除JSON字符串中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的课程

Public List<string> name;
Public List<string> midname;

序列化之后,我将得到以下输出

Once I serialize it I'm getting the following output like

 {"name":[hari],"midname":null}

但是我希望我的答案是这样

But I want my answer to be like this

{"name":[hari]}

它不应该显示具有null值的class属性,而我正在使用c#.net框架.

It shouldn't display the class attribute that has null value and I'm using c# .net framework.

推荐答案

完整答案取决于您如何序列化您的类.

The full answer depends on how you're serializing your class.

如果您使用数据协定来序列化您的类,请设置EmitDefaultValue = false

If you're using data contracts to serialize your classes, set EmitDefaultValue = false

[DataContract]
class MyClass
{
    [DataMember(EmitDefaultValue = false)]
    public List<string> name;

    [DataMember(EmitDefaultValue = false)]
    public List<string> midname { get; set; }
}

如果您使用的是 Json.Net ,请尝试使用此方法

If you're using Json.Net, try this instead

class MyClass
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<string> name;

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<string> midname { get; set; }
}

或使用JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

这篇关于如何删除JSON字符串中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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