Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HttpClient Json serializer to ignore null values

Tags:

json

c#

.net

I'm currently working with a console app which I'm using the HttpClient to interact with an Apache CouchDB database. I'm using this article: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

I'd like to ignore the null properties in my class when I'm serializing and sending a document to my database via the PostAsJsonSync but I'm not sure how:

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;
    }

Here's the class I'm serializing....

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
  }

Any help much appreciated.

like image 545
James Mundy Avatar asked Mar 02 '13 20:03

James Mundy


People also ask

How do I ignore null values in JSON request?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do I ignore null values in post request body in spring boot?

Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!! NOTE : com.

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object.


2 Answers

Assuming that you are using Json.NET to serialize your object, you should use the NullValueHandling property of the JsonProperty attribute

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]

Check out this great article and the online help for more details

like image 132
Julien Jacobs Avatar answered Oct 01 '22 14:10

Julien Jacobs


If you need this behavior for all the properties of all the classes you're going to send (which is exactly the case that has led me to this question), I think this would be cleaner:

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 );
}

This way there's no need to add attributes to your classes, and you still don't have to serialize all the values manually.

like image 43
HellBrick Avatar answered Oct 01 '22 13:10

HellBrick