Deserializing JSON to anonymus type in C#

Binding JSON string to anonyms type

  • Share

JSON is really easy to use and it really boosts performances since it is a lot lighter than XML and SOAP.

Sometime it can be really annoying having to create POCO class every time you need to deserialize JSON value passed from client side in ASP.NET web applications. During extending project functionality this number of POCO classes can significantly grow to that matter that you have a bunch of classes for even the simplest task you have to do with JSON value.

string jsonValue = "{name:\"Dejan\", email:\"dejan@website.com\", website:\"dejanstojanovic.net\"}";
string jsonValue = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(anonymusObject);
    

Ideal way is to use anonymous type for simple cases like this and reduce the number of POCO classes for binding JSON string value to. Serializing an object instance, even anonymous type object is easy just with one line, but from JSON to anonymous type object instance is a bit different.
First thing that pop into my mind is use dynamic. Reading from dynamic instance is not so comfortable.

Since template anonymous instance will be instantiated with all properties marked as readonly, you cannot just simply assign the value. Value of properties are not even accessible by BackingFields as they do not exist in anonymous type. Simply anonymous type property cannot be changed in the runtime.

string jsonValue = "{name:"Dejan", email:"dejan@website.com", website:"dejanstojanovic.net"}";
dynamic dynamicObject = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<dynamic>(jsonValue);
var anonymusObject = new { name = string.Empty, email = string.Empty, website = string.Empty };
anonymusObject.GetType().GetProperty("name").SetValue(anonymusObject, dynamicObject["name"]);
anonymusObject.GetType().GetProperty("email").SetValue(anonymusObject, dynamicObject["email"]);
anonymusObject.GetType().GetProperty("website").SetValue(anonymusObject, dynamicObject["website"]);
    
        An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Property set method not found.

Dynamic reminds me to late binding in VB.NET or boxing. Basically, properties and values are there, but there is no intelisense, so you are dealing with code like 20 years ago. Really not nice way to do coding. Because of these downsizes I decided to go another way.

Luckily for us JSON serializer has overload for deserialize method which accepts string JSON value and type. we can use GetType to get type of anonymus type instance we can use as a template.

string jsonValue = "{name:"Dejan", email:"dejan@website.com", website:"dejanstojanovic.net"}";
var anonymusObject = new { name = string.Empty, email = string.Empty, website = string.Empty };
var a = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonValue, anonymusObject.GetType());
    

Unfortunately, even though compiler was not complaining in runtine, you'll get exception regarding missing parameterless constructor for type you are trying to serialize to

        An unhandled exception of type 'System.MissingMethodException' occurred in System.Web.Extensions.dll
Additional information: No parameterless constructor defined for type of '<>f__AnonymousType0`3[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

It turns out that anonymous types in C# do not have a public parameterless constructor, and thus the operation fails.

The only way so far to deserialize JSON to anonymus type is by using JSON.net library you can fetch as nuget package or direcly from https://json.codeplex.com

string jsonValue = "{name:"Dejan", email:"dejan@website.com", website:"dejanstojanovic.net"}";
var anonymusObject = new { name = string.Empty, email = string.Empty, website = string.Empty };
var a = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonValue, anonymusObject);
    

References

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus