Detect if deserialized object is missing a field with the JsonConvert class in Json.NET

C#.NetJsonSerializationjson.net

C# Problem Overview


I'm trying to deserialize some JSON objects using Json.NET. I've found however that when I deserialize an object that doesn't have the properties I'm looking for that no error is thrown up but a default value is returned for the properties when I access them. It's important that I'm able to detect when I've deserialized the wrong type of object. Example code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Json_Fail_Test
{
    class Program
    {
        [JsonObject(MemberSerialization.OptOut)]
        private class MyJsonObjView
        {
            [JsonProperty("MyJsonInt")]
            public int MyJsonInt { get; set; }
        }

        const string correctData = @"
        {
            'MyJsonInt': 42
        }";

        const string wrongData = @"
        {
            'SomeOtherProperty': 'fbe8c20b'
        }";

        static void Main(string[] args)
        {
            var goodObj = JsonConvert.DeserializeObject<MyJsonObjView>(correctData);
            System.Console.Out.WriteLine(goodObj.MyJsonInt.ToString());

            var badObj = JsonConvert.DeserializeObject<MyJsonObjView>(wrongData);
            System.Console.Out.WriteLine(badObj.MyJsonInt.ToString());
        }
    }
}

The output of this program is: 42 0

I would prefer an exception be thrown to failing silently. Short of that is there a way to detect if the serialization failed to find a parameter?

I know I can parse the data with a Json object and then check for the parameter with a key value lookup but the codebase I'm in uses the pattern above and I'd like keep that consistent if it's possible.

C# Solutions


Solution 1 - C#

The Json.Net serializer has a MissingMemberHandling setting which you can set to Error. (The default is Ignore.) This will cause the serializer to throw a JsonSerializationException during deserialization whenever it encounters a JSON property for which there is no corresponding property in the target class.

static void Main(string[] args)
{
    try
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.MissingMemberHandling = MissingMemberHandling.Error;

        var goodObj = JsonConvert.DeserializeObject<MyJsonObjView>(correctData, settings);
        System.Console.Out.WriteLine(goodObj.MyJsonInt.ToString());

        var badObj = JsonConvert.DeserializeObject<MyJsonObjView>(wrongData, settings);
        System.Console.Out.WriteLine(badObj.MyJsonInt.ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
}

Result:

42
JsonSerializationException: Could not find member 'SomeOtherProperty' on object
of type 'MyJsonObjView'. Path 'SomeOtherProperty', line 3, position 33.

See: MissingMemberHandling setting.

Solution 2 - C#

Just add [JsonProperty(Required = Required.Always)] to the required properties and it'll throw exception if the property is not there while deserializing.

[JsonProperty(Required = Required.Always)]
 public int MyJsonInt { get; set; }

Solution 3 - C#

Put the following attribute on required properties:

[DataMember(IsRequired = true)]

If the member is not present, it will throw a Newtonsoft.Json.JsonSerializationException.

As Brian suggested below, you will also need this attribute on your class:

[DataContract]

Solution 4 - C#

Just define your members in your definition class with a question mark '?' int?:

private class MyJsonObjView
{
    [JsonProperty("MyJsonInt")]
    public int? MyJsonInt { get; set; }
}

When it is not initialized, it will just be null, otherwise it will be a valid value. This allows you to have settings optional and evaluate them on a per-setting basis.

Solution 5 - C#

As @dbc tells in comments:

  • At deserialization: > If your Model has a property that your JSON does not, and you want that to be an error, use [JsonProperty(Required = Required.Always)].

  • At serialization: > If your JSON has a property that your Model does not, and you want that to be an error, use MissingMemberHandling = MissingMemberHandling.Error.

also using [DataMember(IsRequired = true)] for error at deserialization is true when proeprty type is nullable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDubiousPusherView Question on Stackoverflow
Solution 1 - C#Brian RogersView Answer on Stackoverflow
Solution 2 - C#GorvGoylView Answer on Stackoverflow
Solution 3 - C#Adam ModlinView Answer on Stackoverflow
Solution 4 - C#isgoedView Answer on Stackoverflow
Solution 5 - C#Guido MochaView Answer on Stackoverflow