Serializing Null in JSON.Net

How to ignore a property in class if null, using json.net

As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a NullValueHandling property which you can set to ignore.

Here's a sample:

JsonSerializer _jsonWriter = new JsonSerializer {
NullValueHandling = NullValueHandling.Ignore
};

Alternatively, as suggested by @amit

JsonConvert.SerializeObject(myObject, 
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});

Serializing null in JSON.NET

Okay, I think I've come up with a solution (my first solution wasn't right at all, but then again I was on the train). You need to create a special contract resolver and a custom ValueProvider for Nullable types. Consider this:

public class NullableValueProvider : IValueProvider
{
private readonly object _defaultValue;
private readonly IValueProvider _underlyingValueProvider;

public NullableValueProvider(MemberInfo memberInfo, Type underlyingType)
{
_underlyingValueProvider = new DynamicValueProvider(memberInfo);
_defaultValue = Activator.CreateInstance(underlyingType);
}

public void SetValue(object target, object value)
{
_underlyingValueProvider.SetValue(target, value);
}

public object GetValue(object target)
{
return _underlyingValueProvider.GetValue(target) ?? _defaultValue;
}
}

public class SpecialContractResolver : DefaultContractResolver
{
protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
{
if(member.MemberType == MemberTypes.Property)
{
var pi = (PropertyInfo) member;
if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
{
return new NullableValueProvider(member, pi.PropertyType.GetGenericArguments().First());
}
}
else if(member.MemberType == MemberTypes.Field)
{
var fi = (FieldInfo) member;
if(fi.FieldType.IsGenericType && fi.FieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
return new NullableValueProvider(member, fi.FieldType.GetGenericArguments().First());
}

return base.CreateMemberValueProvider(member);
}
}

Then I tested it using:

class Foo
{
public int? Int { get; set; }
public bool? Boolean { get; set; }
public int? IntField;
}

And the following case:

[TestFixture]
public class Tests
{
[Test]
public void Test()
{
var foo = new Foo();

var settings = new JsonSerializerSettings { ContractResolver = new SpecialContractResolver() };

Assert.AreEqual(
JsonConvert.SerializeObject(foo, Formatting.None, settings),
"{\"IntField\":0,\"Int\":0,\"Boolean\":false}");
}
}

Hopefully this helps a bit...

Edit – Better identification of the a Nullable<> type

Edit – Added support for fields as well as properties, also piggy-backing on top of the normal DynamicValueProvider to do most of the work, with updated test

Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings

A "null" value in a JObject is actually a non-null JValue with JValue.Type equal to JTokenType.Null. It represents a JSON value of null when such a value actually appears in the JSON. I believe it exists to capture the difference between the following two JSON objects:

  "source2": {
"z": null
}

"source2": {
}

In the first case, the property "z" is present with a null JSON value. In the second case, the property "z" is not present. Linq-to-JSON represents the first case with a null-type JValue rather than having JProperty.Value actually be null.

To prevent null tokens from creeping into your JObject's values, use the appropriate serializer setting when creating the JObject from some POCO:

var jobj = JObject.FromObject(new
{
x = 1,
y = "bla",
z = (int?)null
}, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore } );

(Note the POCO must not itself already be a JObject. The untyped method(s) JsonConvert.DeserializeObject(jsonString) or JsonConvert.DeserializeObject<dynamic>(jsonString) will by default return a JObject when root JSON container in jsonString is a JSON object.)

Serialize empty object instead of null in Newtonsoft.JSON

To avoid the erros just change bool to bool?

public class MDT
{
[Key]
public string mdtAssetId { get; set; }
public bool? isMDTDownloaded { get; set; }
public bool? isNamingConventionCorrect { get; set; }
}

JsonConvert.SerializeObject: Unexpected result when Serializing null value

The NullValueHandling has to do with null values for a property and not the object it self.

For example, if you have the below example:

public class ExampleClass
{
public string NullProperty { get; set; }
}

And then you serialize it:

var obj = new ExampleClass();
var jsons = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });

Then the NullProperty is ignored and you get {}.

Edited

The reason why "null" is returned is because the RFC for JSON (https://www.rfc-editor.org/rfc/rfc7159) explicitly states the following:

A JSON value MUST be an object, array, number, or string, or one of

the following three literal names:

false null true

The literal names MUST be lowercase. No other literal names are

allowed.

value = false / null / true / object / array / number / string

false = %x66.61.6c.73.65 ; false

null = %x6e.75.6c.6c ; null

true = %x74.72.75.65 ; true

Edited:

I originally had a work around, but I removed it because I really think you should follow the RFC. The RFC clearly stated that a NULL object MUST be represented by a "null" so any work around is not a good idea.

To stay with the RFC, I would store "null" or return "null" and not NULL. When you deserialize "null" it will return a NULL value.

Json.NET Ignore null values in dictionary

I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace JsonSerialize {
public static class Program {
private static Dictionary<string, string> dict = new Dictionary<string, string> {
["A"] = "Some text",
["B"] = null
};

public static void Main(string[] args) {
var filtered = dict
.Where(p => p.Value != null)
.ToDictionary(p => p.Key, p => p.Value);

var json = JsonConvert.SerializeObject(filtered, Formatting.Indented);

Console.WriteLine (json);
}
}
}

Which gives:

{
"A": "Some text"
}

How to remove null values while serializing to Json in C# if only all data members are null

I don't whether it is best solution available but this is I solved this problem.

//Serialize the object to json, if false then removes the null properties else ignore them
private static string Serialize(C JsonObject, bool ignoreNullProperties)
{
return JsonConvert.SerializeObject(JsonObject,
new JsonSerializerSettings { NullValueHandling = ignoreNullProperties == true ? NullValueHandling.Ignore : NullValueHandling.Include, Formatting = Formatting.Indented });
}


public static string SerializePerservingNullValuesForNonEmptyClass(C JsonObject)
{
string notHavingNullValues = Serialize(C, true);// serialized to get json with no null properties
string havingNullValues = Serialize(C, false);// serialized to json with null properties
//converted both Json string to dictionary<string,object>
Dictionary<string, object> notHavingNullValuesDictionary =
JsonConvert.DeserializeObject<Dictionary<string, object>>(notHavingNullValues);
Dictionary<string, object> havingNullValuesDictionary =
JsonConvert.DeserializeObject<Dictionary<string, object>>(havingNullValues);

Dictionary<string, object> resultDictionary =
GetNullValuesForObjectHavingAnyNonNullValues(havingNullValuesDictionary,
notHavingNullValuesDictionary);

return Serialize(resultDictionary, false);
}

//iterated through dictionary having no null value and taking values from dictionary having all values and stored them to a new dictionary
private static Dictionary<string, object> GetNullValuesForObjectHavingAnyNonNullValues(Dictionary<string, object> havingNull, Dictionary<string, object> notHavingNull)
{
Dictionary<string, object> expectedJsonFormat = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> values in notHavingNull)
{
expectedJsonFormat.Add(values.Key, havingNull[values.Key]);
}
return expectedJsonFormat;
}

Hope this helps to everyone.

JSON.Net references become null

I've solved it. Once I added an empty constructor in my Tile class everything works as intended.

public Tile() { } //for deserialization

Ignoring null fields in Json.net

Yes you need to use JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore.

But because structs are value types you need to mark Field2, Field3 nullable to get the expected result:

public struct structA
{
public string Field1;
public structB? Field2;
public structB? Field3;
}

Or just use classes instead of structs.

Documentation: NullValueHandling Enumeration



Related Topics



Leave a reply



Submit