【问题标题】:How to refine json by remove null values properties and zero (0) value properties from the c# object如何通过从 c# 对象中删除空值属性和零 (0) 值属性来优化 json
【发布时间】:2015-02-09 13:13:19
【问题描述】:

场景:

我必须发送一个 Httpwebrequest 并且服务器要求它只接受两个 Json 格式的值,我想向另一台服务器发送一个请求,并且一次需要一个 Json 格式的值。

对于上述场景,我创建了一个类并提供所有三个属性,如下所示

pubilc class MyClass
{
    public string as { get; set;}
    public int value { get; set;}
    public string asd { get;s et;}
}

对于第一个 HttpWebRequest,到第一台服务器,我只想从 MyClass 'as' 和 'asd' 发送两个属性,现在我将通过 NewtonSoft 的 JsonConvert 函数进行序列化,如下所示

MyClass class = new MyClass();
string json = JsonConvert.SerializeObject(class);

上面的语法将返回具有 0 和空值属性的 json,NewtonSoft 提供了从 Json 中删除空值的功能,但它不能删除值为 0 的属性,或者您可以说您的属性数据类型是否为 int并且没有分配任何值,而是将 0 分配给这些属性。

从 Json 中删除 Null 属性的语法

string json = JsonConvert.SerializeObject(class, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

上述语法将在序列化 MyClass 对象期间删除空值。

现在询问如何从 json 中删除属性,如果它的属性为 0。

【问题讨论】:

  • 作为@mgigirey 的回答,将 int 转换为可为空的。我只是想解释为什么它不应该首先删除零。不像null,就像说"It's an error or should be ignored",零通常是一个可接受的值,而不是不寻常的标志。这就是为什么将int 转换为int? 是处理您的情况的正确方法

标签: c# xml json json.net


【解决方案1】:

您可以尝试将您的 int 属性定义为可为空的:

public int? value { get; set;}

【讨论】:

    【解决方案2】:

    修改你的表情

    string json = JsonConvert.SerializeObject(
      class, 
      Newtonsoft.Json.Formatting.Indented, 
      new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }
    );
    

    如下,

    string json = JsonConvert.SerializeObject(
      class, 
      Newtonsoft.Json.Formatting.Indented, 
      new JsonSerializerSettings { 
        NullValueHandling = NullValueHandling.Ignore,
        DefaultValueHandling = DefaultValueHandling.Ignore 
      }
    );
    

    【讨论】:

      【解决方案3】:

      我接受了 mgigirey 给出的答案,我做了另一个解决方案,我将我的 Json 转换为 xml 并删除了值为 0 的节点并再次转换为 Json。我的解决方案也对我有用,但它比 Mgigirey 的回答有点冗长和慢。

      所以这里有两个答案,如果你们有人想采用我的解决方案,那么请参阅以下内容。

      //This line will remove the null as i earlier mentioned in my question.
      string jsonStatus = JsonConvert.SerializeObject(myJson, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
      
      //Create xml object by covnert json into xml
      XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
      
      //Get the property name which have the value 0
      var v = doc.GetElementsByTagName("value")[0];
      
      //Remove the child node.
      doc.DocumentElement.RemoveChild(v);
      
      //Again convert into the json.
      string jsonText = JsonConvert.SerializeObject(doc);
      

      【讨论】:

      • 很高兴能帮上忙。
      • :) 谢谢,如果可行,您也可以投票赞成我的答案。
      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 2015-03-10
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      相关资源
      最近更新 更多