c# - 如何让 HttpClient Json 序列化程序忽略空值

标签 c# .net json

我目前正在使用一个控制台应用程序,我正在使用 HttpClient 与 Apache CouchDB 数据库进行交互。我正在使用这篇文章:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

当我序列化文档并将文档通过 PostAsJsonSync 发送到我的数据库时,我想忽略类中的 null 属性,但我不确定如何:

public static HttpResponseMessage InsertDocument(object doc, string name, string db)
    {
      HttpResponseMessage result;
      if (String.IsNullOrWhiteSpace(name)) result = clientSetup().PostAsJsonAsync(db, doc).Result;
      else result = clientSetup().PutAsJsonAsync(db + String.Format("/{0}", name), doc).Result;
      return result;
    }

    static HttpClient clientSetup()
    {
      HttpClientHandler handler = new HttpClientHandler();
      handler.Credentials = new NetworkCredential("**************", "**************");
      HttpClient client = new HttpClient(handler);
      client.BaseAddress = new Uri("*********************");
      //needed as otherwise returns plain text
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      return client;
    }

这是我正在序列化的类....

class TestDocument
  {
    public string Schema { get; set; }
    public long Timestamp { get; set; }
    public int Count { get; set; }
    public string _rev { get; set; }
    public string _id { get; set; } - would like this to be ignored if null
  }

非常感谢任何帮助。

最佳答案

假设您使用 Json.NET 来序列化您的对象,您应该使用 JsonProperty 属性的 NullValueHandling 属性

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]

看看这个很棒的 articleonline help了解更多详情

关于c# - 如何让 HttpClient Json 序列化程序忽略空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179060/

相关文章:

.net - 如何优化这个简单但可怕的实现?

javascript - 如何访问由 BundleConfig 类创建的物理 Bundled 和 Minified js/css

c# - 使用自定义在数据库中存储不同的用户权限

c# - 有丰富的领域模型示例吗?

jQuery Ajax 响应因无效字符而失败

javascript - 加载 facebook wall feed JSON 问题

java - JSON - 使用 Gson 反序列化动态对象

c# - 我的 C# Reg-ex 正确吗?

c# - 如何筛选 SharePoint 上的列表

c# - DataGrid 具有 WPF 中第 n 级单元格的 DataGrid