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.
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!! NOTE : com.
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
Specifies the settings on a JsonSerializer object.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With