Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 487
DubiousPusher Avatar asked Jan 09 '14 20:01

DubiousPusher


People also ask

Is JSON serialized or Deserialized?

JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.

What is the use of JsonConvert DeserializeObject?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

What is JsonConvert SerializeObject in C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Deserialized JSON?

The process whereby a lower-level format (e.g. that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. In JavaScript, for example, you can deserialize a JSON string to an object by calling the function JSON.


1 Answers

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.

like image 86
Brian Rogers Avatar answered Oct 14 '22 08:10

Brian Rogers