简体   繁体   English

在newtonsoft中反序列化JSON时忽略空值

[英]ignore null values while deserializing JSON in newtonsoft

I have following json coming from server 我有以下来自服务器的json

{
 "contactList":[{

      "contactName":"Jhon",
      "address":null,
      "phone":null,
      "contactId":99932

}]

}

now when i am deserializing using JsonConvert.DeserializeObject<Response>(content) i want following output 现在当我使用JsonConvert.DeserializeObject<Response>(content)反序列化时,我想要以下输出

{
     "contactList":[{

          "contactName":"Jhon",
          "contactId":99932

    }]

    }

i tried following code but its not working 我尝试了以下代码,但无法正常工作

 JsonSerializerSettings jsonSettings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };

this is my Contact model 这是我的联系方式

public class Contact 
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public String address { set; get; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
         public String phone { set; get; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
         public String name { set; get; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
         public String id { set; get; }
  }

model of Response 反应模型

     [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
 public class Response 
    {
         [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<SignodeMSA.Model.Master.Contact> contactsList { get; }
  }

and i am deserializing after fetching it from server 和我从服务器获取后反序列化

  Response responseData = await Task.Run(() => JsonConvert.DeserializeObject<Response>(content, jsonSettings));

I think you need manually delete that properties from json string. 我认为您需要从json字符串中手动删除该属性。

Maybe like this : How do I remove all null and empty string values from a json object? 也许像这样: 如何从json对象中删除所有null和空字符串值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM