10

私は現在、HttpClientを使用してApacheCouchDBデータベースと対話するコンソールアプリを使用しています。私はこの記事を使用しています: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
  }

どんな助けでも大歓迎です。

4

4 に答える 4

15

Json.NETを使用してオブジェクトをシリアル化すると仮定すると、JsonProperty属性のNullValueHandlingプロパティを使用する必要があります

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]

詳細については、このすばらしい記事オンラインヘルプをご覧ください。

于 2013-03-02T20:43:23.043 に答える
13

送信するすべてのクラスのすべてのプロパティに対してこの動作が必要な場合 (これがまさにこの質問につながったケースです)、これはよりクリーンになると思います:

using ( HttpClient http = new HttpClient() )
{
    var formatter = new JsonMediaTypeFormatter();
    formatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

    TestDocument value = new TestDocument();
    HttpContent content = new ObjectContent<TestDocument>( value, formatter );
    await http.PutAsync( url, content );
}

この方法では、クラスに属性を追加する必要がなく、すべての値を手動でシリアル化する必要もありません。

于 2014-04-15T08:04:13.800 に答える
6

HttpClient.PostAsync を使用する

JsonMediaTypeFormatter jsonFormat = new JsonMediaTypeFormatter();
jsonFormat.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
jsonFormat.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

HttpResponseMessage res = c.PostAsync<T>(url, TObj, jsonFormat).Result;
于 2014-05-30T01:42:35.843 に答える
3

PutAsJsonAsyncあなたが今それを持っているので、あなたがそれをすることができるかどうかはわかりません。ただし、 Json.NETを使用できる場合はこれを実行でき、役立つ場合はNuGetパッケージが存在します。使用できる場合は、InsertDocument関数を次のように書き直します。

public static HttpResponseMessage InsertDocument(object doc, string name, string db)
    {
      HttpResponseMessage result;
      string json = JsonConvert.SerializeObject(doc, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
      if (String.IsNullOrWhiteSpace(name)) result = clientSetup().PostAsync(db, new StringContent(json, null, "application/json")).Result;
      else result = clientSetup().PutAsync(db + String.Format("/{0}", name), new StringContent(json, null, "application/json")).Result;
      return result;
    }
于 2013-03-02T20:44:36.460 に答える